I am new to react and I’m working on react fetch using useEffect.
I have a util file which fetches data from an API. I am testing the sad path and the API returns a 400 status code.
below is my fetch code:
export async function getVans() {
const res = await fetch("/api/vans")
if (!res.ok) {
throw Object.assign(new Error("Failed to fetch vans"),{
message: "Failed to fetch vans",
statusText: res.statusText,
status: res.status
});
}
const data = await res.json()
return data.vans
}
I’m using this in my component to set some states.
I’m using a try-catch block while calling this API inside the use effect. But I see that the error is not caught.
useEffect(() => {
async function loadVans() {
setLoading(true)
try {
const data = await getVans()
console.log("fetched data: "+data);
setVans(data)
} catch (err) {
console.log("error :"+err)
setError(err)
} finally {
setLoading(false)
}
}
loadVans()
}, [])
I see it proceeds and breaks with runtime errors.
Here is the link to the project :https://github.com/manjosh1990/react-practice/tree/master/reactive-navigation
I get the error on /vans path.
the file is Vans.jsx
Please advise.
3
Answers
AJAX and APIs – React:
Check out this CodeSandbox that catches the error for your
getVans
function.I wish I could pinpoint what the error is, but it’s hard without a "working" example from your end.