0

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?

1 Answer 1

1

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, []);
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you it worked, in the sense that it stopped the infinite loop. However I still get only 1), 2), 3) (without the log after fetch()) and then the app breaks because is trying to use the returned value of the custom hook, before it got a response. How can I make the hook wait for the response before to return?
I tried this useEffect(async () => {await sendRequest(request);}, []); but it does't work.
the component that uses this hook needs to handle the case where infoFromTheStates is undefined, usually in popular libraries for hook (like Apollo's for example) it's common to return a 'loading' field for that (true when the values are not usable)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.