Answers for "Remove the warning for setState on unmounted components in React"

0

Remove the warning for setState on unmounted components in React

useEffect(() => {
  let isMounted = true;               // note mutable flag
  someAsyncOperation().then(data => {
    if (isMounted) setState(data);    // add conditional check
  })
  return () => { isMounted = false }; // cleanup toggles value, if unmounted
}, []);                               // adjust dependencies to your needs
Posted by: Guest on October-12-2021
0

Remove the warning for setState on unmounted components in React

function useAsync(asyncFn, onSuccess) {
  useEffect(() => {
    let isActive = true;
    asyncFn().then(data => {
      if (isActive) onSuccess(data);
    });
    return () => { isActive = false };
  }, [asyncFn, onSuccess]);
}
Posted by: Guest on October-12-2021

Code answers related to "Remove the warning for setState on unmounted components in React"

Code answers related to "Javascript"

Browse Popular Code Answers by Language