In React Native, a PUT API request is used to update an existing resource on a server. It commonly replaces the entire object with new data and is widely used in RESTful APIs.
fetch() or AxiosContent-TypeA PUT request sends updated data to a specific endpoint. The server identifies the resource using an ID in the URL.
// Basic structure of a PUT request using fetch
fetch("https://example.com/api/users/1", {
method: "PUT",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
name: "John Doe",
email: "john@example.com"
})
});
// Updating user data using PUT API in React Native
const updateUser = async () => {
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@email.com"
})
});
const data = await response.json();
console.log(data);
};
The server receives the updated object and responds with the modified data. In most APIs, the full updated resource is returned as JSON.
Imagine a profile edit screen on a mobile device where the user updates their name and email. Pressing the Save button triggers a PUT request to update the profile on the server.
// Button click triggers PUT request
<Button title="Save Profile" onPress={updateUser} />
try/catch