In my authentication flow the user should be redirected to the Home Screen after they have fetched the token from the API and if they logout it should redirect them back to the Login Screen. Unfortunately, it doesn’t do that. I had to hot restart the app, & then it redirects to the correct screen.
App.js
const App = () => {
const [token, setToken] = React.useState(false);
useEffect (() => {
getData();
});
const getData = async () => {
const value = await AsyncStorage.getItem('@user_auth');
if(value !== null) {
setToken(true);
}
}
return (
<NavigationContainer>
{token == false ? (
<Stack.Navigator initialRouteName="LoginScreen" screenOptions={{headerShown: false}}>
<Stack.Screen name="LoginScreen" component={LoginScreen} />
<Stack.Screen name="RegistrationScreen" component={RegistrationScreen} />
</Stack.Navigator>
) : (
<Stack.Navigator initialRouteName="HomeScreen" screenOptions={{headerShown: false}}>
<Stack.Screen name="HomeScreen" component={HomeScreen} />
</Stack.Navigator>
)}
</NavigationContainer>
);
};
LoginScreen
const storeData = async (accessToken, tokenType) => {
try {
await AsyncStorage.setItem('@access_token', accessToken);
await AsyncStorage.setItem('@token_type', tokenType);
await AsyncStorage.setItem('@user_auth', tokenType + " " + accessToken);
} catch (e) {
console.log(e);
}
}
const _userLogin = () => {
fetch(URLs._login, {
method: "POST",
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
},
body: JSON.stringify({
email: inputs.email,
password: inputs.password,
})
}).then((response) => response.json())
.then(async (result) => {console.log(result);
if(result.message !== "Unauthorized / Access Token Expired" && result.message !== "The given data was invalid."){
storeData(result.access_token, result.token_type)
} else {
Alert.alert("Error", result.message);
}
});
};
CustomModal.js (User press on a modal to logout)
const [inputs, setInputs] = React.useState({
userAuth: '',
});
useEffect (() => {
getData();
}, []);
const getData = async () => {
inputs.userAuth = await AsyncStorage.getItem('@user_auth');
//console.log("retrive");
}
const _logout = () => {
fetch(URLs._logout, {
method: "GET",
headers: {
'Authorization': inputs.userAuth,
'Content-Type': 'application/json',
},
}).then((response) => response.json())
.then((result) => {
console.log(result);
if(result.message == "Successfully logged out"){
AsyncStorage.clear();
navigation.popToTop();
}
Alert.alert("Logout", result.message);
});
};
const logoutAlert = () => {
Alert.alert(
"Logout",
"Do you want to logout?",
[
{text: 'Yes', onPress: () => _logout()},
{text: 'No', onPress: undefined, style: 'cancel'},
],
{
cancelable: true
}
);
}