React Does Not Wait For Server Call To Complete And Throws Error
Solution 1:
No. there is no need to introduce any delay/wait. That is already handled by the async/await syntax.
You can either set an initial value in your useState or early return a custom message if
nocs
is undefined.If you are fetching from your own api, you can return a response with an error if the fetch request should fail. And then at client side, you can handle that error by wrapping your fetch call inside a try-catch block
import {useEffect, useState } from'react'exportconstNoc = () => {
const [nocs, setNoc] = useState();
useEffect(
() => {
const fetchNoc = async () => {
const response = awaitfetch('http://localhost:8080/countrydefinitions');
const data = await response.json();
setNoc(data);
};
try{
fetch()
}catch(error){
//handle error hereconsole.log(error);
}
},[]
);
if(!nocs){
return (<p>No NOC found</p>)
}
return<div><div>NOC LIST</div>
{nocs.map(noc => <div>{noc.region}</div>)}
</div>
}
Solution 2:
React will rerender when the props change. Indeed at the beginning its nothing yet.
2 things to make it more solid can be done.
- Add a default value, so that map is available on the array.
const [nocs, setNoc] = useState([]);
- And/Or wait until noc is not undefined anymore, and validating that It has a map function, before trying to use map.
{nocs && typeof nocs.map === 'function' && nocs.map(noc =><div>{noc.region}</div>)}
Solution 3:
at first render, nocs
has no data then useEffect runs and the second render, nocs
will have data.
you need to check if nocs
is undefined
{nocs && nocs.length > 0 && nocs.map(noc => <div>{noc.region}</div>)}
Post a Comment for "React Does Not Wait For Server Call To Complete And Throws Error"