Scenario:
I have a Login.js that I show as a Modal from multiple screens wherever I have placed the check to see if a user is logged in or not. After the user successfully login I change a key called LoggedIn to 1 from 0 using AsyncStorage. Now when a user successfully logged in and the Modal closes I want to rerender the scree user is on.
As I have a background in iOS, so there we have viewDidAppear that runs every time there is a Modal or user opens another app and comes back to the screen, etc.
So, what would be the equivalent of that in React Native? When a Modal close it should check if the LoggedIn value is changed in AsyncStorage and I've already prepared the components to render accordingly to the value of LoggedIn value.
Code:
I have a screen Profile.js in which I'm checking:
AsyncStorage.getItem("LoggedIn").then((value) => {
if (value === "1") {
setNeedLogin(true)
} else {
setNeedLogin(false)
}
});
const [needLogin, setNeedLogin] = useState(false);
Based on the above state I'm rendering the view as:
{
!needLogin &&
<View>
<Text>{userName}</Text>
<Text>{userEmail}</Text>
<TouchableOpacity>
<Text>Logout</Text>
</TouchableOpacity>
</View>
}
{
needLogin &&
<View>
<Text>You are not logged in</Text>
<Text>Please login or create a new account to see more information.</Text>
<TouchableOpacity onPress={() => {
alert('I am showing login screen here which is a modal')
}}>
<Text>Login or Sign Up</Text>
</TouchableOpacity>
</View>
}
Now when the Login.js renders the Modal and use logs in upon successful login I change the value of LoggedIn to 1 and close the modal which shows the Profile.js screen but when it shows it the view doesn't rerender. So, how would I check and change the state every time the profile.js view appears?