componentDidMount
is a life-cycle method. Navigating from Screen1 to Screen2 does NOT unmount Screen1. So, when you come back from Screen 2 to Screen 1, the Screen 1 does not mounting because it was NOT unmounted. Hence, componentDidMount
is not called.
Whats's the correct way of doing this?
You should use Context API
. When you load from AsyncStorage
, set that value to Context as well. When you update the value, write changes to both AsyncStorage and Context.
PS: The AsyncStorage
may not needed. It depends on your requirement. Most probably, you will be able to achieve this only with Context API
.
Please check the following snack. It is done using hooks. You can do the same using class components.
https://snack.expo.io/3L9QSqWqt
UPDATE:
If the data to be handled is too large, it is not recommended to use Context since it saves all the data in the device RAM and consuming too much RAM may result in app crash.
To do this without using context:
(1) Define a function to retrieve data from AsyncStorage
.
loadData() {
AsyncStorage.getItem("userChats").then((value) => {
this.setState({userChats: JSON.parse(value)});
});
}
(2) Call it in componentDidMount
.
componentDidMount() {
this.loadData()
}
(3) When navigating to the Screen2, pass a callback function as a prop to call loadData
function.
this.props.navigation.navigate('Screen2', {
onGoBack: () => this.loadData(),
});
(4) Then in the Screen2, before goBack
, you can do this:
await AsyncStorage.setItem('userChats', updatedData);
this.props.navigation.state.params.onGoBack();
this.props.navigation.goBack();
Then, the loadData
function is called in the screen2.
PS: Since you use state
to store the retrieved data from the AsyncStorage
, you can also directly load them into the Context and use. But, keep in mind that, using too much of RAM may cause app crash.