EN
React / Axios - GET request
3 points
In this article, we would like to show you how to make Axios GET requests in React.
Note: it is required to add external library to run below example, so use:
xxxxxxxxxx
1npm install axios
In the example below, we use async
-await
, but you might as well do it on promises.
xxxxxxxxxx
1
import React from 'react'
2
import axios from 'axios'
3
4
const App = () => {
5
const handleClick = async () => {
6
try {
7
const response = await axios.get('https://jsonplaceholder.typicode.com/todos/4');
8
if (response.status === 200) {
9
console.log(response.data);
10
} else {
11
console.error('Status 200 expected.');
12
}
13
} catch(error) {
14
console.error(error);
15
}
16
};
17
return (
18
<div>
19
<button onClick={handleClick}>Click to send GET request</button>
20
</div>
21
);
22
};
23
24
export default App;
Note: {JSON} Placeholder provides free testing API that works locally when you copy it.
Online runnable example: codesandbox.io