Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

React Native, add two return statements to useEffect hook

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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) => ({
        ...
    }));
};

>Solution :

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
        } 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading