首页 > 解决方案 > 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();
}, []);

标签: javascriptreactjs

解决方案


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.


推荐阅读