- read

How to Use async/await in useEffect()

Xiuer Old 66

function useEffect(effect: EffectCallback, deps?: DependencyList): void;
type EffectCallback = () => (void | (() => void | undefined));

According to the documentation and ts prompts, useEffect the callback parameter returns a clean-up function that clears side effects. Therefore, it is impossible to return Promise, let alone useasync/await

useEffect(() => {
const subscription = props.source.subscribe();
return () => {
// Clean up the subscription
subscription.unsubscribe();
};
});

"At this time, you can choose to wrap another layer of async function, place it in the callback function of useEffect, and use async/await in disguise."

async function fetchMyAPI() {
let response = await fetch('api/data')
response = await res.json()
dataSet(response)
}

useEffect(() => {
fetchMyAPI();
}, []);

In Plain English

Thank you for being a part of our community! Before you go: