Languages
[Edit]
EN

React - Axios - POST request

0 points
Created by:
Dirask JS Member
3460

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:

npm install axios

Axios POST request example

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.

import React from 'react'
import axios from 'axios'

const App = () => {
    const userToPost = {
        title: 'foo',
        body: 'bar',
        userId: 1,
    };

    const handleClick = async () => {
        const response = await axios
            .post('https://jsonplaceholder.typicode.com/posts', userToPost)
            .catch((error) => console.log('Error: ', error));
        if (response && response.data) {
            console.log(response);
            console.log(response.data);
        }
    };
    return (
        <div>
            <button onClick={handleClick}>Click to send POST request</button>
        </div>
    );
};

export default App;

Online runnable example: 

codesandbox.io

React - axios

Native Advertising
­čÜÇ
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

ÔŁĄ´ŞĆ­čĺ╗ ­čÖé

Join