Published: April 22 2021

React + Axios - HTTP PUT Request Examples

Below is a quick set of examples to show how to send HTTP PUT 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 PUT request with a JSON body using axios

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

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

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


PUT request using axios with React hooks

This sends the same PUT 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 send the HTTP PUT 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(() => {
    // PUT request using axios inside useEffect React hook
    const article = { title: 'React Hooks PUT Request Example' };
    axios.put('https://reqres.in/api/articles/1', article)
        .then(response => setUpdatedAt(response.data.updatedAt));

// 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-put-request-examples-axios?file=App/PutRequestHooks.jsx


PUT request using axios with async/await

This sends the same PUT 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() {
    // PUT request using axios with async/await
    const article = { title: 'React Put Request Example' };
    const response = await axios.put('https://reqres.in/api/articles/1', article);
    this.setState({ updatedAt: response.data.updatedAt });
}

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


PUT request using axios with error handling

This sends a PUT 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() {
    // PUT request using axios with error handling
    const article = { title: 'React PUT Request Example' };
    axios.put('https://reqres.in/invalid-url', article)
        .then(response => this.setState({ updatedAt: response.data.updatedAt }))
        .catch(error => {
            this.setState({ errorMessage: error.message });
            console.error('There was an error!', error);
        });
}

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


PUT request using axios with set HTTP headers

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

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

Example React component at https://stackblitz.com/edit/react-http-put-request-examples-axios?file=App/PutRequestSetHeaders.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