I am writing a react-native app which needs to store a string before it's getting closed or background. When the app starts, it needs to retrieve the string again. (I am using expo for development)
I tried to store the data in componentWillUnmount(), however the function is not called when I close the app.
This is the function to store data.
_storeData = async () => {
try {
await AsyncStorage.setItem('data', 'savedData2');
console.log("done storing");
} catch (error) {
console.log(error)
}};
I am calling storeData() as below:
componentWillUnmount() {
console.log("unmount")
this._storeData();
}
First, I thought it doesn't store data because I am calling an asynchronous function in componentWillUnmount() which might be cancelled before finished, however I don't receive the unmount log either.
There's no way to detect when the app is closed in react-native.
You can detect when the app goes in background using AppState, try checking it out in the docs: https://facebook.github.io/react-native/docs/appstate
I'm using a slightly modified version of the code from the docs found here that works well.
On the component in which you want to save the data when going to background you can add something like this:
componentDidMount() {
AppState.addEventListener('change', this._handleAppStateChange);
this._recoverData();
}
componentWillUnmount() {
AppState.removeEventListener('change', this._handleAppStateChange);
}
_handleAppStateChange = (nextAppState) => {
if (nextAppState === 'background' || nextAppState === 'inactive') {
this._storeData('dataToSave');
}
};
With AppState you will be able to control when the app goes to background and also when it becomes 'active' again.
The _recoverData and _storeData that I call inside those pieces of code are async functions that use the AsyncStorage, so your method shouldn't be a problem.
Additionally, on the docs you can find this note:
This example will only ever appear to say "Current state is: active" because the app is only visible to the user when in the active state, and the null state will happen only momentarily.
Which could be the reason why you don't receive the unmount log (I haven't tried it though).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With