Melly
Melly

Reputation: 745

Why is my fetch request giving me a lot of error in a very short amount of time

So I had to make a fetch call every time I load a page and the page will remain on a loading state until the data is fetched. So I made a function on a separate file the function takes 3 argument (link, setState for Data, setState for loading) and the function looked like this:

        async function fetchingObj(link, dataFunc, loadingFunc){

    const headers = {
        'Content-Type': 'application/json',
        'Authorization': `JWT ${localStorage.getItem('access')}`
    }

    try{

        let data = await fetch(link, { headers }).then(data => data.json())

        if(typeof data === "object" || typeof data === "string"){
           
            dataFunc(data)
            loadingFunc(false)
        }

        else{
            setTimeout( fetchingObj(), 1500 )
            console.log('from else', data);
        }
    }
    
    catch(err){
        setTimeout( fetchingObj(), 1500 )
    }
}

and I imported it to my page and called it inside my useEffect

useEffect(() =>{
    fetchingObj(process.env.REACT_APP_API_URL + `/api/polls/${parameters.num}/`, setPoll, setLOading)
    //eslint-disable-next-line react-hooks/exhaustive-deps
}, [])

So the purpose of this function is that if my server went down the page is going to stay on a loading state and keep refetching every 1,5 sec until my server is back up and running. However when I tested it by turning off my server I got like 100 error per second like thisenter image description here and when my server is back on I still need a refresh, why is this happening?

thank you so much

Upvotes: 2

Views: 409

Answers (2)

gerrod
gerrod

Reputation: 6627

The problem is your call to setTimeout - you're invoking the function immediately rather than queueing the function to run after 1500 milliseconds.

setTimeout( fetchingObj(), 1500 )

This should be -

setTimeout(fetchingObj, 1500);

Or ideally you should be calling it with the same arguments (I'm guessing?) -

setTimeout(() => fetchingObj(link, dataFunc, loadingFunc), 1500)

Here's a stackblitz that shows the problem and the solution.

Upvotes: 1

TheRakeshPurohit
TheRakeshPurohit

Reputation: 551

As the ReactJS officially announces in Github issue it won't work as you have written.

try following

useEffect(() => {
  async function fetchingObj(link, dataFunc, loadingFunc) {
    const headers = {
      "Content-Type": "application/json",
      Authorization: `JWT ${localStorage.getItem("access")}`,
    };

    try {
      let data = await fetch(link, { headers }).then((data) => data.json());

      if (typeof data === "object" || typeof data === "string") {
        dataFunc(data);
        loadingFunc(false);
      } else {
        setTimeout(fetchingObj(), 1500);
        console.log("from else", data);
      }
    } catch (err) {
      setTimeout(fetchingObj(), 1500);
    }
  }

  fetchingObj(
    process.env.REACT_APP_API_URL + `/api/polls/${parameters.num}/`,
    setPoll,
    setLOading,
  );
}, []);

Upvotes: 0

Related Questions