2

I am using react hooks to fetch data but it doesn't seems to stop.

I've read the doc and it mentions that if adding [] as the second argument of useEffect, it will have zero dependency and thus be only called once. I've done this, but it doesn't change the situation and the fetching function is being called numerous times as it printed. Is it a bug?

useEffect(() => {
    props.fetchSounds();
  }, []);


export const fetchSounds = () => {
  console.log("I am being called");
  return dispatch => {
    fetch("http://localhost:4000/sounds")
      .then(response => response.json())
      .then(response => {
        dispatch({
          type: ActionTypes.FETCH_SOUNDS,
          payload: response.data
        });
      })
      .catch(err => console.error(err));
  };
};

Edit: The component is only used once.

Edit: I've tried various things with the hook dependency but none of them can stop the fetch function being called. Like

Let sound become the dependency:

  useEffect(() => {
    props.fetchSounds();
  }, [props.sounds]);

Let a dummy const be the dependency:

  const a = 5;

  useEffect(() => {
    props.fetchSounds();
  }, [a]);

Even without useEffect but just call

  props.fetchSounds()

inside the functional component for once. All of them turns out to be that the fetch function is being called numerous times.

Natalia
  • 153
  • 1
  • 8
  • Is the same component used more than once? – charlietfl Jul 22 '19 at 18:01
  • Then the component it is in probably gets added to the page multiple times. Could you show the component and the parent? Also you never call the arrow function (`dispatch => ...`) so there are no network requests done – Jonas Wilms Jul 22 '19 at 18:02
  • @JonasWilms It's a project with multiple Routes so there are functions like mapDispatchToProps that I didn't paste here ... basically it is doing network request and fetching data correctly but it just doesn't stop lol – Natalia Jul 22 '19 at 18:16
  • Hi i think this link can help with your problem [link](https://stackoverflow.com/questions/53070970/infinite-loop-in-useeffect) – leart morina Jul 22 '19 at 18:17
  • @Natalia did you ever solve this? I'm having the same issue – Red Baron May 09 '20 at 14:11

0 Answers0