Home > Mobile >  Stop setInterval function set inside useEffect
Stop setInterval function set inside useEffect

Time:06-07

I have this simple useEffect code. When the user logged in to the application every 2 minutes I will dispatch an action which is an API call, and I need to stop this interval once a user is logged out. Still, the current code even runs after the user is logged out, what shall I do to prevent this interval when the user logs out.

I am using the value from the localStorage to determine whether the user is logged in or not.

 const intervalId = useRef(null)
    useEffect(() => {
    const isLoggedIn = localStorage.getItem("isUserLoggedIn")  //(true or false)
    intervalId.current = setInterval(() => {
    dispatch(refreshUserToken());
    if(isLoggedIn === false){
    clearInterval(intervalId.current)
    }
    },1000*60*2)

return () => {
clearInterval(intervalId.current)
}
    },[])

Is there any way to resolve my issue? Any help would be much appreciated!!

CodePudding user response:

You should be adding the line where you get that value from localStorage inside the interval, if you want the updated value. Also, localStorage would gives you a string instead of a boolean, either you parse it, or you change your if statement. Try with this:

const intervalId = useRef(null);
useEffect(() => {
  intervalId.current = setInterval(() => {
    const isLoggedIn = localStorage.getItem("isUserLoggedIn"); //(true or false)
    if (isLoggedIn === "false") {
      clearInterval(intervalId.current);
      return;
    }
    dispatch(refreshUserToken());
  }, 1000 * 60 * 2);

  return () => {
    clearInterval(intervalId.current);
  };
}, []);

You could use an event instead of a setInterval. As an example, change the code where you are setting the localStorage to this:

localStorage.setItem("isUserLoggedIn", true); // or false depending on the context
window.dispatchEvent(new Event("storage")); // you notice that there is a change

You change your useEffect to this:

useEffect(()=>{
    const listenStorageChange = () => {
       const isLoggedIn = localStorage.getItem("isUserLoggedIn");
       console.log(isLoggedIn);
       // do your logic here
    };
    window.addEventListener("storage", listenStorageChange);
    return () => window.removeEventListener("storage", listenStorageChange);
},[])

CodePudding user response:

The keys and the values stored with localStorage are always in the UTF-16 string format. As with objects, integer keys and booleans are automatically converted to strings.

So you have to call like this:

if(isLoggedIn === 'false'){
    clearInterval(intervalId.current)
}

Check the documentation.

  • Related