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

164
Visualizações
How to save data to LocalForage from within React component before Route changes?

I want to save some data to localForage from within my component before the route changes as I don't have any global / top-level state. I don't want to save every time the user makes a change, but only when the user is about to leave the current component / route. I've read two ways to do this.

First, I read that I can call functions in the useEffect return(), but it seems that since localForage calls are asynchronous, the data won't be saved in time. The application will go to the new route before the data is saved. The way I tried looks like this:

useEffect(() => {
    
  return () => {
    localForage.setItem(name, item)
    .then(() => {
       console.log("I didn't save in time.");
    });
  };
}, []);

Second, I've read about executing tasks before leaving a route using the onLeave hooks as described here.

These hooks are useful for various things like requiring auth when a route is entered and saving stuff to persistent storage before a route unmounts.

This sounds like what I need, but the function or command I want to run is located in my component and has to be called from my App.js file like this.

<Switch>
  ...
  <Route
    path = '/mypath'
    onLeave={functionToCall} 
  /> 
</Switch>

So it seems I can't call the component's functions from the App.js file.

My question is, can either of these approaches work for me? If not, what can I do to save data to localForage before the route changes?

about 4 years ago · Juan Pablo Isaza
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