In React.js, the fetch API is commonly used to make HTTP requests from the client side. Here's a guide on how to use fetch for different types of requests: GET, POST, PUT, and DELETE.
1. GET Request
To fetch data from a server (e.g., getting data from an API), use a GET request.
import React, { useEffect, useState } from 'react';
function App() {
const [data, setData] = useState(null);
useEffect(() => {
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => setData(data))
.catch(error => console.error('Error fetching data:', error));
}, []);
return (
<div>
<h1>Data from API</h1>
{data && <pre>{JSON.stringify(data, null, 2)}</pre>}
</div>
);
}
export default App;
2. POST Request
To send data to a server, use a POST request.
import React from 'react';
function App() {
const sendData = () => {
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'John Doe', age: 30 }),
})
.then(response => response.json())
.then(data => console.log('Success:', data))
.catch(error => console.error('Error:', error));
};
return (
<div>
<h1>Send Data to API</h1>
<button onClick={sendData}>Send Data</button>
</div>
);
}
export default App;
3. PUT Request
To update existing data on the server, use a PUT request.
import React from 'react';
function App() {
const updateData = () => {
fetch('https://api.example.com/data/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ name: 'Jane Doe', age: 25 }),
})
.then(response => response.json())
.then(data => console.log('Updated:', data))
.catch(error => console.error('Error:', error));
};
return (
<div>
<h1>Update Data</h1>
<button onClick={updateData}>Update Data</button>
</div>
);
}
export default App;
4. DELETE Request
To remove data from the server, use a DELETE request.
import React from 'react';
function App() {
const deleteData = () => {
fetch('https://api.example.com/data/1', {
method: 'DELETE',
})
.then(response => response.json())
.then(data => console.log('Deleted:', data))
.catch(error => console.error('Error:', error));
};
return (
<div>
<h1>Delete Data</h1>
<button onClick={deleteData}>Delete Data</button>
</div>
);
}
export default App;
Key Points
useEffect is used to perform side-effects in functional components, such as fetching data when the component mounts.
- All request types can handle errors using
.catch.
fetch returns a promise, which can be handled using .then for processing the response.
- For POST and PUT requests, include headers and body in the
fetch options.
Remember to replace 'https://api.example.com/data' with your API endpoint and modify headers/body according to your API specifications.