Context: I'm trying to do the authentication of the users when they sing-in getting the token from the backend and storing them in SecureStore to later depending in if it is stored the token navigates to the profile screen or to the register and login screen. In react-native:
The code to access to the register or profile screen depending in if it has the token stored or not:
const MusicScreen = () => {
//Constante de navegación
const navigation = useNavigation();
//Estado para sacar el token de asyncStorage
const [token, setToken] = useState(null);
//Saca el token y lo almacena temporalmente en setToken
const getToken = async () => {
try {
const storedToken = await SecureStore.getItemAsync('token');
setToken(storedToken);
console.log(storedToken)
} catch (error) {
console.error('Error al obtener el token:', error);
}
};
const handleIconPress = () => {
getToken();
if (token === null) {
navigation.navigate('Register');
} else {
navigation.navigate('Profile');
}
};
return (
<View >
<LinearGradient
colors={['#c501e2','#fe0ab7','#ae3dff','transparent']} style={styles.Background}>
<TouchableOpacity onPress={handleIconPress} style={styles.touchable}>
<Image source={require('../files-logos/D-Corchea.png')} style={styles.image}/>
</TouchableOpacity>
</LinearGradient>
</View>
)};
Then, the code to logout on the Profile Screen:
const logout = async() => {
try{
await SecureStore.deleteItemAsync('token');
const storedToken = await SecureStore.getItemAsync('token');
console.log(storedToken);
}catch(e){
console.log('Error trying to delete de token:', e);
}
}
const ProfileScreen= () => {
const navigation = useNavigation();
return (
<View>
<Background1/>
<Text style={{fontWeight:'bold',}}>THis is the profile screen</Text>
<Button title='logout' onPress={()=>{
logout();
navigation.navigate('Register');
}} />
</View>
)};
export default ProfileScreen;
The problem it's that it does not work entirely properly, because it update the value in SecureStore correctly but it navigates properly the second time you click-it.
I've tried the useEffect, but the useEffect is use to update the value when it renders de component, no when it clicks them.