Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!