EN
React - Axios - POST request
0 points
In this article, we would like to show you how to make Axios POST 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.
Note: we are making a request to jsonplaceholder, so the example will work when you copy it.
xxxxxxxxxx
1
import React from 'react'
2
import axios from 'axios'
3
4
const App = () => {
5
const userToPost = {
6
title: 'foo',
7
body: 'bar',
8
userId: 1,
9
};
10
11
const handleClick = async () => {
12
const response = await axios
13
.post('https://jsonplaceholder.typicode.com/posts', userToPost)
14
.catch((error) => console.log('Error: ', error));
15
if (response && response.data) {
16
console.log(response);
17
console.log(response.data);
18
}
19
};
20
return (
21
<div>
22
<button onClick={handleClick}>Click to send POST request</button>
23
</div>
24
);
25
};
26
27
export default App;
Online runnable example: