javascriptreactjsasynchronousreact-hooks

How to call an async function inside useEffect() in React?


I would like to call an async function and get the result for my UseEffect.

The fetch api examples I found on the internet are directly made in the useEffect function. If my URL changes, I must patch all my fetchs.

When I tried, I got an error message.

This is my code.


    async function getData(userId) {
        const data = await axios.get(`http://url/api/data/${userId}`)
            .then(promise => {
                return promise.data;
            })
            .catch(e => {
                console.error(e);
            })
            return data;
    }
    

    function blabla() {
        const [data, setData] = useState(null);
    
        useEffect(async () => {
            setData(getData(1))
        }, []);
    
        return (
            <div>
                this is the {data["name"]}
            </div>
        );
    }

index.js:1375 Warning: An effect function must not return anything besides a function, which is used for clean-up. It looks like you wrote useEffect(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately:

useEffect(() => {
  async function fetchData() {
    // You can await here
    const response = await MyAPI.getData(someId);
    // ...
  }
  fetchData();
}, [someId]); // Or [] if effect doesn't need props or state

Solution

  • Create an async function inside your effect that wait the getData(1) result then call setData():

    useEffect(() => {
      const fetchData = async () => {
         const data = await getData(1);
         setData(data);
      }
    
      fetchData();
    }, []);