Published: November 02 2020

React + Fetch - 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 fetch() which comes bundled with all modern browsers.

Other HTTP examples available:


Simple PUT request with a JSON body using fetch

This sends an HTTP PUT request to the JSONPlaceholder api which is a fake online REST api that includes a /posts/:id route that responds to PUT requests with the contents of the request body and the post id property. The id from the response is assigned to the react component state property postId so it can be displayed in the component render() method.

componentDidMount() {
    // Simple PUT request with a JSON body using fetch
    const requestOptions = {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: 'React PUT Request Example' })
    };
    fetch('https://jsonplaceholder.typicode.com/posts/1', requestOptions)
        .then(response => response.json())
        .then(data => this.setState({ postId: data.id }));
}

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


PUT request using fetch with React hooks

This sends the same PUT request from React using fetch, 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 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 fetch inside useEffect React hook
    const requestOptions = {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: 'React Hooks PUT Request Example' })
    };
    fetch('https://jsonplaceholder.typicode.com/posts/1', requestOptions)
        .then(response => response.json())
        .then(data => setPostId(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-put-request-examples-fetch?file=App/PutRequestHooks.jsx


PUT request using fetch with async/await

This sends the same PUT request from React using fetch, 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).

useEffect(() => {
    // PUT request using fetch with async/await
    async function updatePost() {
        const requestOptions = {
            method: 'PUT',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ title: 'React Hooks PUT Request Example' })
        };
        const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', requestOptions);
        const data = await response.json();
        setPostId(data.id);
    }

    updatePost();
}, []);

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


PUT request using fetch with error handling

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

The fetch() function will automatically throw an error for network errors but not for HTTP errors such as 4xx or 5xx responses. For HTTP errors we can check the response.ok property to see if the request failed and reject the promise ourselves by calling return Promise.reject(error);. This approach means that both types of failed requests - network errors and http errors - can be handled by a single catch() block.

useEffect(() => {
    // PUT request using fetch with error handling
    const requestOptions = {
        method: 'PUT',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ title: 'React Hooks PUT Request Example' })
    };
    fetch('https://jsonplaceholder.typicode.com/invalid-url', requestOptions)
        .then(async response => {
            const data = await response.json();

            // check for error response
            if (!response.ok) {
                // get error message from body or default to response status
                const error = (data && data.message) || response.status;
                return Promise.reject(error);
            }

            setPostId(data.id);
        })
        .catch(error => {
            setErrorMessage(error);
            console.error('There was an error!', error);
        });
}, []);

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


PUT request using fetch with set HTTP headers

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

useEffect(() => {
    // PUT request using fetch with set headers
    const requestOptions = {
        method: 'PUT',
        headers: { 
            'Content-Type': 'application/json',
            'Authorization': 'Bearer my-token',
            'My-Custom-Header': 'foobar'
        },
        body: JSON.stringify({ title: 'React Hooks PUT Request Example' })
    };
    fetch('https://jsonplaceholder.typicode.com/posts/1', requestOptions)
        .then(response => response.json())
        .then(data => setPostId(data.id));
}, []);

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