Home > Net >  React Native, add two return statements to useEffect hook
React Native, add two return statements to useEffect hook

Time:03-14

How can I add two return statements to my useEffect hook? I would like to add an event listener to my current hook.

Event listener:

const subscription = AppState.addEventListener("change", nextAppState => {
  if (
    appState.current.match(/inactive|background/) &&
    nextAppState === "active"
  ) {
    console.log("App has come to the foreground!");
  }

  appState.current = nextAppState;
  setAppStateVisible(appState.current);
  console.log("AppState", appState.current);
});

return () => {
  subscription.remove();
};

Current hook:

useEffect(() => {

    async function checkRefresh() {
        if (
            daysDiffToNow(lastUpdatedTimestamp) > 0 &&
            appState.current.match(/inactive|background/) &&
            nextAppState === "active"
        ) {
            await onRefreshAppData();
        }
    }
    checkRefresh();

    const updateLastUpdatedTextCallback = (value) => {
        setState((prevState) => ({
            ...
        }));
    };
    const id = setInterval(() => {
        updateLastUpdatedTextCallback(lastUpdatedTimestamp);
    }, TIME_INTERVAL_IN_MILISECONDS);
    return () => clearInterval(id);
}, [lastUpdatedTimestamp]);

const close = () => {
    setState((prevState) => ({
        ...
    }));
};

CodePudding user response:

You could simply put them top to bottom inside the useEffect and have a return function that would look like this (it executes at once the code for the two return statements needed) :

 return () => {
          subscription.remove();  // the first
          clearInterval(id);     // the second
        } 
  • Related