React JS PUT Request
A PUT request is used in HTTP to update or replace a resource on the server. In React, making a PUT request typically involves sending updated data to a server using either the native fetch
API or a library like axios
. Here’s a detailed guide on how to handle PUT requests in React:
1. Using fetch
API
The fetch
API allows you to make PUT requests by specifying the method and including the updated data in the request body.
Basic Usage
Example:
import React, { useState } from 'react';
function UpdateData() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const handleUpdate = async () => {
setLoading(true);
try {
const response = await fetch('https://api.example.com/data/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json', // Specify the content type
},
body: JSON.stringify({ key: 'updatedValue' }), // Updated data
});
if (!response.ok) {
throw new Error('Network response was not ok'); // Handle HTTP errors
}
const result = await response.json(); // Parse JSON response
setData(result); // Set the result to state
} catch (error) {
setError(error); // Set error to state if an error occurs
} finally {
setLoading(false); // Set loading to false once the request is complete
}
};
return (
<div>
<button onClick={handleUpdate} disabled={loading}>
{loading ? 'Updating...' : 'Update'}
</button>
{error && <p>Error: {error.message}</p>}
{data && <pre>{JSON.stringify(data, null, 2)}</pre>}
</div>
);
}
export default UpdateData;
2. Using axios
Axios simplifies making PUT requests and handling responses. It provides a more feature-rich API compared to fetch
.
Installation
npm install axios
# or
yarn add axios
Basic Usage
Example:
import React, { useState } from 'react';
import axios from 'axios';
function UpdateData() {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const handleUpdate = async () => {
setLoading(true);
try {
const response = await axios.put('https://api.example.com/data/1', {
key: 'updatedValue', // Updated data
}, {
headers: {
'Content-Type': 'application/json', // Specify the content type
},
});
setData(response.data); // Set the result to state
} catch (error) {
setError(error); // Set error to state if an error occurs
} finally {
setLoading(false); // Set loading to false once the request is complete
}
};
return (
<div>
<button onClick={handleUpdate} disabled={loading}>
{loading ? 'Updating...' : 'Update'}
</button>
{error && <p>Error: {error.message}</p>}
{data && <pre>{JSON.stringify(data, null, 2)}</pre>}
</div>
);
}
export default UpdateData;
Key Points
Request Method:
- For PUT requests, set the
method
to'PUT'
.
- For PUT requests, set the
Headers:
Content-Type: application/json
: Indicates that the data being sent is in JSON format.
Body:
fetch
: Usebody: JSON.stringify(data)
to send updated data as a JSON string.axios
: Pass the updated data directly as the second argument toaxios.put
.
Handling State:
loading
: Tracks whether the request is in progress.error
: Handles any errors that occur during the request.data
: Stores the response data from the server.
Error Handling:
- Proper error handling ensures that your application can manage issues such as network errors or invalid responses gracefully.
Button and State:
- Disable the button while the request is being processed and provide user feedback.
Summary
A PUT request in React is used to update or replace resources on the server. You can use either the native fetch
API or the axios
library to perform PUT requests. Both methods involve specifying the request method as 'PUT'
, setting appropriate headers, and sending updated data in the request body. Managing loading and error states effectively ensures a good user experience and robust application behavior.