Before the Fetch API most of the React JS developers used to depend on the Axios to get the data from the server. Now, with the Fetch API being supported by the most of the browsers, many developers wants to use this instead of Axios as the Fetch API is native to the browsers and there will be no need to depend on third party library.
One of the common requirement in many applications is to send a request to the server to get data when the application is started. The most common place in React JS application to do this task is inside an useEffect hook with an empty array as its dependency which basically makes the hook run only during the initial run of the application.
Using Fetch API with then & catch in useState hook in React Application
The traditional way of getting the data or error from the promise is by using then and catch.
Code:
import React, { useState, useEffect } from 'react'
function FetchAPI() {
const [users, setUsers] = useState([])
const [isError, setIsError] = useState(false);
useEffect(() => {
fetch('https://jsonplaceholder.typicode.com/users').then((response) => {
if (response.ok) {
return response.json();
} else {
throw 'Error getting users list'
}
}).then((data) => {
setUsers(data);
}).catch((error) => {
setIsError(true)
})
}, [])
return (
<div>
{isError ? <h3> Error! Please try again later</h3> :
<ul>
{users.map((user) => <li key={user.id} > {user.name} </li>)}
</ul>
}
</div>
)
}
export default FetchAPI
Notice how we returned the data or an error message, based on the response in the first then callback function. One important thing to note about fetch API is, if there is an error like 404, the then callback function gets executed and the callback function inside catch do not get executed. So, based on the response from the server, we need to either get the data from the response or throw an error message which goes to the catch block.
In the above example, we checked the ok property of the response. Instead of this, you can check the response status ( for example 200, 404 or 500 etc.,) and take appropriate action.
How to use Fetch API async – await with try – catch in useEffect hook in React Application
Another commonly used way with fetch API is to use with async and await. In order to handle the errors, we can use this with try-catch in our application.
example:
import React, { useState, useEffect } from 'react'
function FetchAPI() {
const [users, setUsers] = useState([])
const [isError, setIsError] = useState(false);
useEffect(() => {
const fetchData = async () => {
try {
let response = await fetch('https://jsonplaceholder.typicode.com/users');
if (response.status === 200) {
let data = await response.json();
setUsers(data);
} else {
throw 'Error fetching users list'
}
} catch (error) {
setIsError(true)
}
}
fetchData();
}, [])
return (
<div>
{isError ? <h3> Error! Please try again later</h3> :
<ul>
{users.map((user) => <li key={user.id} > {user.name} </li>)}
</ul>
}
</div>
)
}
export default FetchAPI
in the example above, we have checked for the status code of the response instead of ok property as we did in the first example. Here we checked only against 200 status, in a real time application, you may have to check it against several other status codes also such as 201, 404 or 500 etc.,
Leave A Comment