How to Update Data with Fetch API in React
This article explains how to update data using the Fetch API within a React application. You will learn how to configure asynchronous HTTP PUT and PATCH requests, send JSON payloads to an API endpoint, and update your React component’s state to reflect these changes in the user interface.
Understanding HTTP Methods for Updates
When updating data on a server, you typically use one of two HTTP methods:
- PUT: Replaces the entire target resource with the new payload.
- PATCH: Applies partial modifications to the resource.
Both methods require you to specify the method in your
Fetch configuration, set the appropriate headers, and serialize your
data into a JSON string.
Step-by-Step Implementation in React
To update data, you need to handle the asynchronous request inside a React component and update the local state once the API returns a successful response.
Here is a practical example of a component that updates user profile information:
import React, { useState } from 'react';
function UpdateUserProfile() {
// 1. Initialize local state with default data
const [user, setUser] = useState({ name: 'John Doe', email: 'john@example.com' });
const [isUpdating, setIsUpdating] = useState(false);
const [error, setError] = useState(null);
// 2. Create the update handler function
const handleUpdate = async () => {
setIsUpdating(true);
setError(null);
try {
// 3. Perform the Fetch PUT request
const response = await fetch('https://jsonplaceholder.typicode.com/users/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
id: 1,
name: 'Jane Doe',
email: 'jane@example.com',
}),
});
if (!response.ok) {
throw new Error('Network response was not ok');
}
// 4. Parse the response and update React state
const updatedUser = await response.json();
setUser(updatedUser);
} catch (err) {
setError(err.message);
} finally {
setIsUpdating(false);
}
};
return (
<div>
<h2>User Profile</h2>
{error && <p style={{ color: 'red' }}>Error: {error}</p>}
<p><strong>Name:</strong> {user.name}</p>
<p><strong>Email:</strong> {user.email}</p>
<button onClick={handleUpdate} disabled={isUpdating}>
{isUpdating ? 'Updating...' : 'Update Profile to Jane Doe'}
</button>
</div>
);
}
export default UpdateUserProfile;Key Elements of the Fetch Update Request
When executing the update logic, pay close attention to these three core configurations:
1. The Method Property
By default, the Fetch API performs GET requests. You
must explicitly declare the method as PUT or
PATCH in the configuration object:
method: 'PUT'2. Request Headers
Servers need to know the format of the incoming data. Always include
the 'Content-Type': 'application/json' header to indicate
you are sending JSON data:
headers: {
'Content-Type': 'application/json',
}3. The Body Payload
JavaScript objects cannot be sent directly over HTTP. You must
convert your data payload into a string using
JSON.stringify() before assigning it to the body:
body: JSON.stringify(data)Best Practices
- Error Handling: Always check
response.okbefore parsing the JSON data. The Fetch API does not reject promises on HTTP error status codes (like 404 or 500). - Loading States: Disable action buttons during the request to prevent duplicate submissions from the user.
- Optimistic Updates: For a faster user experience, you can update the UI state immediately before the network request finishes, reverting it only if the Fetch request fails.