How to catch login error? React Nactivate

Asked

Viewed 377 times

0

How to display a friendly message to the user when the login did not work, I tried several ways but could not. Only works if the email and password is correct.

const response = await api.post('/login', { email: email, senha: senha });

const { auth = false, token, msg } = response.data;

 if (auth) {
      await AsyncStorage.setItem('token', token);
       navigation.navigate('Tarefas', { token: token });
   } else {
      Alert.alert('Erro de Login', 'Não foi possivel fazer o login');
      setIsLoading(false)
   }

1 answer

1

What should be occurring is that when you enter the wrong email or password, the return does not have the information you expect. By your code, you expect to receive auth, token and msg of the login request. If auth and msg return in any answer, the problem may be that token is only generated in case of success.

One way to make the friendly message appear would be to use a Try/catch. Here’s an example:

try {
	const response = await api.post('/login', { email: email, senha: senha });
	const { auth } = response.data;
	if (auth) { 
		const { token, msg } = response.data;
		await AsyncStorage.setItem('token', token); 
		navigation.navigate('Tarefas', { token: token }); 
	} else { 
		Alert.alert('Erro de Login', 'Não foi possivel fazer o login'); 
		setIsLoading(false) 
	}
} catch (err) {
	Alert.alert('Erro de Login', 'Não foi possivel fazer o login'); 
	console.log("Error:" + err.message);
	
}

  • thank you very much worked out

Browser other questions tagged

You are not signed in. Login or sign up in order to post.