In React.js, you can use the fetch API to make different types of HTTP requests—GET, POST, PUT, DELETE, etc.—to interact with a server or API. Here’s how you can handle each of these types of requests:
1. 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:', error));
}, []);
return (
<div>
{data ? JSON.stringify(data) : 'Loading...'}
</div>
);
}
export default App;
2. POST Request
import React, { useState } from 'react';
function App() {
const [response, setResponse] = useState(null);
const postData = () => {
fetch('https://api.example.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'value' })
})
.then(response => response.json())
.then(data => setResponse(data))
.catch(error => console.error('Error:', error));
};
return (
<div>
<button onClick={postData}>Send POST Request</button>
{response && <div>Response: {JSON.stringify(response)}</div>}
</div>
);
}
export default App;
3. PUT Request
import React, { useState } from 'react';
function App() {
const [response, setResponse] = useState(null);
const updateData = () => {
fetch('https://api.example.com/data/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ key: 'updatedValue' })
})
.then(response => response.json())
.then(data => setResponse(data))
.catch(error => console.error('Error:', error));
};
return (
<div>
<button onClick={updateData}>Send PUT Request</button>
{response && <div>Response: {JSON.stringify(response)}</div>}
</div>
);
}
export default App;
4. DELETE Request
import React, { useState } from 'react';
function App() {
const [response, setResponse] = useState(null);
const deleteData = () => {
fetch('https://api.example.com/data/1', {
method: 'DELETE'
})
.then(response => response.json())
.then(data => setResponse(data))
.catch(error => console.error('Error:', error));
};
return (
<div>
<button onClick={deleteData}>Send DELETE Request</button>
{response && <div>Response: {JSON.stringify(response)}</div>}
</div>
);
}
export default App;
Common Practices
- Error Handling: Always handle errors by catching them using
.catch().
- Async/Await: You can simplify
.then() chains by using async/await for cleaner code.
- State Management: Use React’s
useState and useEffect hooks to manage component state and handle side effects, such as fetching data.
- Headers: Often, you'll need to include headers such as
Content-Type and possibly authorization headers.
- JSON Conversion: Use
.json() for converting responses when dealing with JSON APIs.
These examples demonstrate how to use fetch with common request methods. Depending on your application's complexity, you might want to further modularize your fetching logic or even use libraries like Axios, which provide additional convenience for HTTP requests.