Original link: https://bobbyhadz.com/blog/react-send-request-on-click
Author: Borislav Hadzhiev
The text starts here~
Overview
In React, make an http request with a click event:
- Set the
onClick
attribute on the element. - Whenever an element is clicked, make an http request.
- Update
state
variable and re-render the data.
If you use axios
, scroll down to the next code snippet.
import {useState} from 'react';
const App = () => {
const [data, setData] = useState();
const [isLoading, setIsLoading] = useState(false);
const [err, setErr] = useState('');
const handleClick = async () => {
setIsLoading(true);
try {
const response = await fetch('<https://reqres.in/api/users>', {
method: 'POST',
body: JSON.stringify({
name: 'John Smith',
job: 'manager',
}),
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
});
if (!response.ok) {
throw new Error(`Error! status: ${response.status}`);
}
const result = await response.json();
console.log('result is: ', JSON.stringify(result, null, 4));
setData(result);
} catch (err) {
setErr(err.message);
} finally {
setIsLoading(false);
}
};
console.log(data);
return (
<div>
{err && <h2>{err}</h2>}
<button onClick={handleClick}>Make request</button>
{isLoading && <h2>Loading...</h2>}
{data && (
<div>
<h2>Name: {data.name}</h2>
<h2>Job: {data.job}</h2>
</div>
)}
</div>
);
};
export default App;
fetch
The above example shows us how, in React, an HTTP POST
request can be sent on the click of a button.
We set the onClick
attribute on the button
element, so whenever the button is clicked, the handleClick
function will be called. We marked the handleClick
function with the ---febc1bfa7325ed04871c2215820884a7 async
keyword, so we can use the await
keyword to wait for the inner Promise to return.
In thehandleClick
function, we wait for thePOST
request to complete and update thestate
variable.
The example uses the native fetch
API, but the concept also applies if you use the axios
dependency package.
axios
Here's how to use the axios
package to make a http POST
request when a button is clicked.
If you decide to use axios
, make sure you have installed the package by running npm install axios
.
import {useState} from 'react';
import axios from 'axios';
const App = () => {
const [data, setData] = useState();
const [isLoading, setIsLoading] = useState(false);
const [err, setErr] = useState('');
const handleClick = async () => {
setIsLoading(true);
try {
const {data} = await axios.post(
'<https://reqres.in/api/users>',
{name: 'John Smith', job: 'manager'},
{
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
},
);
console.log(JSON.stringify(data, null, 4));
setData(data);
} catch (err) {
setErr(err.message);
} finally {
setIsLoading(false);
}
};
console.log(data);
return (
<div>
{err && <h2>{err}</h2>}
<button onClick={handleClick}>Make request</button>
{isLoading && <h2>Loading...</h2>}
{data && (
<div>
<h2>Name: {data.name}</h2>
<h2>Job: {data.job}</h2>
</div>
)}
</div>
);
};
export default App;
The above example shows us how to use axios
to make a http POST
request when the button is clicked.
If you useaxios
, make sure you have runnpm install axios
in the project root to install the package.
The syntax when using the axios
package is a bit cleaner and we have fewer implementation details to deal with, but the concept is the same.
We have to set the onClick
attribute on a button element and make an HTTP request each time the button is clicked.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。