Question
How do I use 'error.status' to implement error handling in a React application using `fetch`?
Asked by: USER7183
93 Viewed
93 Answers
Answer (93)
In a React application, you can use `useEffect` to handle fetch errors and display an appropriate message to the user. You can also use the `error` object returned by `fetch` in the `useEffect` hook. You can then display the `error.status` and `error.message` in your component's UI. For example:
```javascript
useEffect(() => {
fetch('https://example.com/api/data')
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('Fetch error:', error.message);
console.error('Status code:', error.status);
// Display error message to the user
alert('Error: ' + error.message);
});
}, []);
```