0
0
ReactHow-ToBeginner · 4 min read

How to Make PUT Request in React: Simple Guide with Example

In React, you can make a PUT request using the fetch API by specifying the method as PUT and including the data in the body as a JSON string. Use async/await inside a function or useEffect hook to handle the request and response.
📐

Syntax

The basic syntax for a PUT request in React using fetch is:

  • url: The API endpoint where you want to update data.
  • method: Set to PUT to update existing data.
  • headers: Usually includes Content-Type: application/json to tell the server you are sending JSON.
  • body: The data you want to update, converted to a JSON string.
javascript
fetch('https://api.example.com/item/1', {
  method: 'PUT',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
💻

Example

This example shows a React functional component that updates user data with a PUT request when a button is clicked. It uses async/await for clarity and handles the response and errors.

javascript
import React, { useState } from 'react';

export default function UpdateUser() {
  const [message, setMessage] = useState('');

  async function handleUpdate() {
    try {
      const response = await fetch('https://jsonplaceholder.typicode.com/users/1', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          name: 'Updated Name',
          email: 'updated@example.com'
        })
      });
      if (!response.ok) {
        throw new Error('Network response was not ok');
      }
      const data = await response.json();
      setMessage('User updated: ' + JSON.stringify(data));
    } catch (error) {
      setMessage('Error: ' + error.message);
    }
  }

  return (
    <div>
      <button onClick={handleUpdate}>Update User</button>
      <p>{message}</p>
    </div>
  );
}
Output
User updated: {"id":1,"name":"Updated Name","email":"updated@example.com"}
⚠️

Common Pitfalls

  • Forgetting to set Content-Type header to application/json causes the server to not parse the data correctly.
  • Not converting the data to a JSON string with JSON.stringify before sending in body.
  • Ignoring error handling can make debugging difficult if the request fails.
  • Using GET or other methods by mistake instead of PUT.
javascript
/* Wrong way: Missing JSON.stringify and headers */
fetch('https://api.example.com/item/1', {
  method: 'PUT',
  body: { name: 'New Name' } // This is an object, not a string
});

/* Right way: */
fetch('https://api.example.com/item/1', {
  method: 'PUT',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'New Name' })
});
📊

Quick Reference

Remember these key points when making PUT requests in React:

  • Use method: 'PUT' in fetch options.
  • Always set Content-Type header to application/json.
  • Convert your data object to JSON string with JSON.stringify().
  • Handle errors with try/catch or .catch().
  • Use async/await for cleaner asynchronous code.

Key Takeaways

Use fetch with method 'PUT' and include JSON stringified data in the body.
Always set 'Content-Type' header to 'application/json' for JSON data.
Handle errors to avoid silent failures and improve debugging.
Use async/await for clear and readable asynchronous code.
Remember to convert your data object to a JSON string before sending.