Pete
Pete

Reputation: 3451

How to simplify an async call inside a React useEffect Hook

I'm trying to create the simplest React Hook useEffect call I can and hoping not to have to create a function call inside useEffect. My code is below and it requires me to call fetchData() to make it work. Is there a simpler version of this?

Maybe with a strategically placed async keyword or something like that?

useEffect(() => {
  const fetchData = async () => {
      let result = await axios.get('http://localhost:4000/');
      console.log(result.data.length);
  };
  fetchData();
}, []);

Upvotes: 1

Views: 218

Answers (1)

Elias Schablowski
Elias Schablowski

Reputation: 2812

What you can do is make it an IIFE:

useEffect(() => {
  const promise = (async () => {
      let result = await axios.get('http://localhost:4000/');
      console.log(result.data.length);
  })();
  return (() => {
    promise.then(() => cleanup());
  });
}, []);

Or use plain promises:

useEffect(() => {
  const promise = axios.get('http://localhost:4000/').then((result) => {
      console.log(result.data.length);
  });
  return (() => {
    promise.then(() => cleanup());
  })
}, []);

But that is about as much as you can do since useEffect cannot be async directly. From ESLint:

Effect callbacks are synchronous to prevent race conditions.

Upvotes: 1

Related Questions