Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

418
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda