Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

416
Vistas
Stop setInterval function set inside useEffect

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!!

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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);
},[])
about 4 years ago · Juan Pablo Isaza Denunciar

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda