简体   繁体   中英

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();
}, []);

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.

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