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?