Published: July 17 2020

React + Axios - HTTP POST Request Examples

Below is a quick set of examples to show how to send HTTP POST requests from React to a backend API using the axios HTTP client which is available on npm.

Other HTTP examples available:


Installing axios from npm

With the npm CLI: npm install axios

With the yarn CLI: yarn add axios


Simple POST request with a JSON body using axios

This sends an HTTP POST request to the Reqres api which is a fake online REST api that includes a generic /api/<resource> route that responds to POST requests for any <resource> with the contents of the post body and a dynamic id property. This example sends an article object to the /api/articles route and then assigns the id from the response to the react component state property articleId so it can be displayed in the component render() method.

componentDidMount() {
    // Simple POST request with a JSON body using axios
    const article = { title: 'React POST Request Example' };
    axios.post('https://reqres.in/api/articles', article)
        .then(response => this.setState({ articleId: response.data.id }));
}

Example React component at https://stackblitz.com/edit/react-http-post-request-examples-axios?file=App/PostRequest.jsx


POST request using axios with React hooks

This sends the same POST request from React using axios, but this version uses React hooks from a function component instead of lifecycle methods from a traditional React class component. The useEffect React hook replaces the componentDidMount lifecycle method to make the HTTP POST request when the component loads.

The second parameter to the useEffect React hook is an array of dependencies that determines when the hook is run, passing an empty array causes the hook to only be run once when the component first loads, like the componentDidMount lifecyle method in a class component. For more info on React hooks see https://reactjs.org/docs/hooks-intro.html.

useEffect(() => {
    // POST request using axios inside useEffect React hook
    const article = { title: 'React Hooks POST Request Example' };
    axios.post('https://reqres.in/api/articles', article)
        .then(response => setArticleId(response.data.id));

// empty dependency array means this effect will only run once (like componentDidMount in classes)
}, []);

Example React hooks component at https://stackblitz.com/edit/react-http-post-request-examples-axios?file=App/PostRequestHooks.jsx


POST request using axios with async/await

This sends the same POST request from React using axios, but this version uses an async function and the await javascript expression to wait for the promises to return (instead of using the promise then() method as above).

async componentDidMount() {
    // POST request using axios with async/await
    const article = { title: 'React POST Request Example' };
    const response = await axios.post('https://reqres.in/api/articles', article);
    this.setState({ articleId: response.data.id });
}

Example React component at https://stackblitz.com/edit/react-http-post-request-examples-axios?file=App/PostRequestAsyncAwait.jsx


POST request using axios with error handling

This sends a POST request from React using axios to an invalid url on the api then assigns the error message to the errorMessage component state property and logs the error to the console.

componentDidMount() {
    // POST request using axios with error handling
    const article = { title: 'React POST Request Example' };
    axios.post('https://reqres.in/invalid-url', article)
        .then(response => this.setState({ articleId: response.data.id }))
        .catch(error => {
            this.setState({ errorMessage: error.message });
            console.error('There was an error!', error);
        });
}

Example React component at https://stackblitz.com/edit/react-http-post-request-examples-axios?file=App/PostRequestErrorHandling.jsx


POST request using axios with set HTTP headers

This sends the same POST request again from React using axios with a couple of headers set, the HTTP Authorization header and a custom header My-Custom-Header.

componentDidMount() {
    // POST request using axios with set headers
    const article = { title: 'React POST Request Example' };
    const headers = { 
        'Authorization': 'Bearer my-token',
        'My-Custom-Header': 'foobar'
    };
    axios.post('https://reqres.in/api/articles', article, { headers })
        .then(response => this.setState({ articleId: response.data.id }));
}

Example React component at https://stackblitz.com/edit/react-http-post-request-examples-axios?file=App/PostRequestSetHeaders.jsx

 


Need Some React Help?

Search fiverr for freelance React developers.


Follow me for updates

On Twitter or RSS.


When I'm not coding...

Me and Tina are on a motorcycle adventure around Australia.
Come along for the ride!


Comments


Supported by