简体   繁体   中英

Infinite loop using fetch() in a custom react hook

I am making my first custom hook,for now it should just send a GET request. This is the hook:

const useMyCustomHook = request => {
  
  // I have a couple of useState() here

  const sendRequest = async () => {

    // I set the states here

    try {
      console.log("2) This log shows up.");
      const response = await fetch(request.url);
      console.log("This does NOT shows up.");
      if (!response.ok) throw new Error('Something went wrong');

      // I reset the states here

    } catch(error) {
      console.log(error);
    }
  }; // end sendRequest()

  console.log("1) This log shows up.");
  sendRequest();
  console.log("3) This log shows up.");

  return {infoFromTheStates}
};

And that's how I call it: (The actual url is a bit different)

const response = useSendRequest({url: 'https://react-http-b228c-default-rtdb.europe-west1.firebasedatabase.app/tasks.json'});

When I run the app I get an infinite loop and I get the logs in the order I named them: first I get 1) then 2) and 3) , then again 1) and so on...
It's like I never arrive to get a response from fetch() .

I don't even know if the problem is my understanding of async/await or of some React logic.

Anyone knows what's going on?

Each time the component runs, it calls this custom hook, which makes a fetch and then change the state, which makes the component run and it calls the hook and so on.

You need to use useEffect so that it will only run the fetch once: change

  sendRequest();

to:

useEffect(sendRequest, []);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM