I am trying to make a full stack Transport management system with mern but it runs fine for 15s and after that TypeError: Failed to fetch comes in and it increases exponentially in my console.
useEffect(() => {
const fetchBus = async () => {
try{
const response = await fetch("/api/buses");
const json = await response.json();
if (response.ok) {
dispatch({ type: "SET_BUS", payload: json });
}
}
catch(error){
console.log(error)
}
};
fetchBus();
}, [handleOwnership,handleAvailable]);
2
Answers
I figured it out. I was getting into a death-loop because I added functions in my dependencies but I learned that one should never do that instead of function add variables or arrays or primitives in dependencies. For me I used use-state (variable) in dependencies instead of functions
As
fetch()
andresponse.json()
both are asynchronous tasks and both returns a Promise.You need to parse json data inside an if(response.ok){} block:Replace:
Fetch JSON GET Request:
Fetch JSON POST Request: