0

So i am updating state in a useEffect hook and getting this error i dont how to use cleanup function if we use async/await syntax in a useEffect hooks

Error :Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in %s.%s, a useEffect cleanup function,


  const getToken = async () => {
    const mytoken = await AsyncStorage.getItem("fb_token");
    if (mytoken) {
      navigation.navigate("Main", { screen: "Map" });
      setToken(mytoken);
    } else {
      setToken(false);
    }
  };
    getToken();

  }, [navigation]);```

How to update state and use clean up function should i declare this function outside hook but if i do that how would i use that function as a clean up?
Yash Gupta
  • 135
  • 2
  • 10

1 Answers1

5

You can get a callback when the component is unmounting or remounting as a result of one of the useEffect dependencies changing, by returning a function from useEffect. You can use that to set a flag to let yourself know things have changed. See *** comments:

useEffect(() => {
    let cancelled = false; // *** A flag to let us know this is cancelled

    const getToken = async () => {
        const mytoken = await AsyncStorage.getItem("fb_token");
        if (!cancelled) { // *** Check the flag
            if (mytoken) {
                navigation.navigate("Main", { screen: "Map" });
                setToken(mytoken);
            } else {
                setToken(false);
            }
        }
    };
    getToken().catch(error => {                 // ***
        // Handle/report error here...          // *** Handle errors from the async function
    });                                         // ***

    // *** A callback to let us know to set the flag
    return () => {
        cancelled = true;
    };
}, [navigation]);

(You're also breaking one of the rules of promises, flagged above: Always either handle errors, or pass the promise chain onto something that will.)

Note that as I mentioned earlier, that will skip setting the token in two situations:

  1. The component unmounted (the one that was causing you trouble)

  2. navigation changed

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875