skip to Main Content

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


  1. Chosen as BEST ANSWER

    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


  2. As fetch() and response.json() both are asynchronous tasks and both returns a Promise.You need to parse json data inside an if(response.ok){} block:

    Replace:

     useEffect(() => {
    
     const fetchBus = async () => {
    
     try{
    
       const response = await fetch("/api/buses");
       //const json = await response.json();//Not here
       
       if (response.ok) {
        const json = await response.json();//But Here
        dispatch({ type: "SET_BUS", payload: json });
       }
     
     }
     catch(error){
       console.log(error)
      }
     };
    
     fetchBus(); 
     }, [handleOwnership,handleAvailable]);
    

    Fetch JSON GET Request:

    let url = 'https://someurl.com';
    
    let response = await fetch(url);
    let responseOK = response && response.ok;
    if (responseOK) {
        let data = await response.json();
        // do something with data
    }
    

    Fetch JSON POST Request:

    let url = 'https://someurl.com';
    let options = {
                method: 'POST',
                mode: 'cors',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json;charset=UTF-8'
                },
                body: JSON.stringify({
                    property_one: value_one,
                    property_two: value_two
                })
            };
    let response = await fetch(url, options);
    let responseOK = response && response.ok;
    if (responseOK) {
        let data = await response.json();
        // do something with data
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search