乐闻世界logo
搜索文章和话题

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

1个答案

1

Directly invoking an asynchronous function within the useEffect hook can lead to issues because useEffect does not allow direct return of a promise. However, you can define an async function inside useEffect and call it immediately. For example:

jsx
import React, { useEffect, useState } from 'react'; function MyComponent() { const [data, setData] = useState(null); useEffect(() => { // Define an async function const fetchData = async () => { try { const response = await fetch('https://api.example.com/data'); const result = await response.json(); setData(result); } catch (error) { console.error('Fetching data error:', error); } }; // Call the async function fetchData(); }, []); // Empty array ensures the effect runs only once on component mount // Render component return ( <div> {data ? ( <div>{JSON.stringify(data)}</div> ) : ( <div>Loading...</div> )} </div> ); } export default MyComponent;

In the above example, fetchData inside useEffect is an async function responsible for fetching data. It is called immediately after definition. Note that by passing an empty array as the second argument to useEffect, we ensure that the effect runs only once when the component mounts.

Additionally, if your asynchronous logic requires cleanup when the component unmounts, you can return a cleanup function from useEffect, but this cleanup function cannot be async. If necessary, handle cancellation or cleanup of asynchronous operations within the cleanup function. For example:

jsx
useEffect(() => { let isActive = true; const fetchData = async () => { try { const response = await fetch('https://api.example.com/data'); if (isActive) { const result = await response.json(); setData(result); } } catch (error) { if (isActive) { console.error('Fetching data error:', error); } } }; fetchData(); // Cleanup function return () => { isActive = false; }; }, []);

In this example, we use an isActive variable to track the component's mounted state. If the component unmounts before the data request completes, we use isActive to prevent calling setData or console.error. This avoids executing these operations after the component has unmounted, thus preventing potential memory leaks.

2024年6月29日 12:07 回复

你的答案