1

I'm struggling with using EventListener and data fetching in the useEffect hook.

What i'm trying to achieve is fetching my data once in the useEffect using the getData function. but at the same time using my EventListener every time I press my keys.

When I try the code below, my EventListener won't work. But my getData function will only be executed once (what i need)

  useEffect(() => {
    getData();

    window.addEventListener('keydown', keyDownHandler);

    return () => {
      window.removeEventListener('keydown', keyDownHandler);
    }
  }, []);

But when I try this code, my EventListener works but It keeps executing the getData function. meaning it will just keep fetching data until my browser crashen

  useEffect(() => {
    getData();

    window.addEventListener('keydown', keyDownHandler);

    return () => {
      window.removeEventListener('keydown', keyDownHandler);
    }
  });

Here are the other 2 functions:

  const getData =  () => {
    axios.get(`https://myapi`)
      .then((res) => {
       setResults(res.data)
      })
  }
  const keyDownHandler = (e) => {
    if (e.keyCode === 37) console.log('prev')
    else if (e.keyCode === 39) console.log('next')
  }

I have no idea how to fix this, I have read this similar question but it still doesn't solve my problem, unless I'm missing something

Yorbjörn
  • 356
  • 3
  • 21

1 Answers1

2

you can do multiple useEffects with different dependencies.

useEffect(() => {
    getData();
}, []);

useEffect(() => {
    window.addEventListener('keydown', keyDownHandler);

    return () => {
      window.removeEventListener('keydown', keyDownHandler);
    }
});
ian
  • 1,112
  • 1
  • 5
  • 15