Home > front end >  Return Postman error message to user on failed login/reg React-Native
Return Postman error message to user on failed login/reg React-Native

Time:05-03

enter image description here

enter image description here

My backend is set up with validations, which I want to return to the user on failed attempts.The top picture is what I am currently returning. The picture below that one (what my postman returns) is one such error message I want to return to a user on a failed login attempt in my try/catch block. I would prefer to do this via the Alert.alert() method. The following is my loginUser code:

enter code hexport interface LoginRequest {
 name: string;
 pass: string;
}

export const loginUser = async (
  request: LoginRequest,
  onSuccess: (user: User) => void,
  one rror: (error: any) => void,
) => {
  console.log(request);

try {
  await logout();

const loginResponse: AxiosResponse<LoginResponse> = await login(request);

const loginResponseData: LoginResponse = loginResponse.data;
console.log('userAuth: ', loginResponseData);

await AsyncStorage.setItem('access_token', loginResponseData.access_token);
await AsyncStorage.setItem('logout_token', loginResponseData.logout_token);
await AsyncStorage.setItem('csrf_token', loginResponseData.csrf_token);

const userId = loginResponseData.current_user.uid;
const userResponse: AxiosResponse<User> = await getUser(userId);
console.log('user response:', userResponse);
onSuccess(userResponse.data);
} catch (error: any) {
  console.log('Login error: '   JSON.stringify(error));
  console.log();
  one rror(error);
  }
};

CodePudding user response:

You can access the body of the response of an Axios 4xx error with error.response.data. Simply use the below line:

onError(error?.response?.data?.message || error);
  • Related