Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Axios Unhandled Promise Rejection

I ve got a problem with axios in my react-native app. The error message is provided here Pic1 Pic2 Actions.start() never runs.

Edit 1: Heres the full code. Edit 2: Picture of the error messagePic3 As to the results the const res= await... should be the problem. Have to add more details, otherwise I cant update this question ;)

export const apiPostLogin = (
 accountData
) => async dispatch => {
dispatch(setFetching(true));
try {
  var instance = axios.create({
    baseURL: 'https://api.xxxx.de/',
    timeout: 1000
 });

const res = await axios.post('/api/v1/auth/login', accountData);
Actions.Start();

dispatch(setAuthToken(res.data.token));


  await dispatch(apiGetAccount(res.data.token));
  console.log(res);
} catch (error) {
  console.log(error.response);
  dispatch(setFetching(false));
  if (error.response.status === 401) {
  dispatch(
    setApiResponse({
      apiResponse: true,
      didShowResponse: false,
      apiResponseError: true,
      apiResponseCode: 401,
      apiResponseMessage: 'E-Mail und Passwort stimmen nicht überein'
    })
  );
} else if (error.response.status === 417) {
  dispatch(
    setApiResponse({
      apiResponse: true,
      didShowResponse: false,
      apiResponseError: true,
      apiResponseCode: 417,
      apiResponseMessage: 'Du hast Deine E-Mail noch nicht bestätigt'
    })
  );
} else {
  dispatch(
    setApiResponse({
      apiResponse: true,
      didShowResponse: false,
      apiResponseError: true,
      apiResponseCode: 499,
      apiResponseMessage:
        'Du kannst Dich im Moment nicht bei uns anmelden. Wir befinden   uns im Wartungsmodus'
    })
   );
   }
  }
  };
like image 375
lernen7 Avatar asked Dec 06 '25 22:12

lernen7


1 Answers

Wrap the post call in a try catch (catch is essential for handling rejected promises) block. Your network request is getting failed. You need to catch the error / handle the promise rejection

    try {
        const res = await axios.post('/api/v1/auth/login', accountData);
        console.log('Success!');
        console.log(res.status);
        console.log(res.data);
    } catch (e) {
        console.error('Failure!');
        console.error(e.response.status);
        throw new Error(e);
    }
    Actions.Start();

OR try using axios() instead of axios.create()

return axios.({
    method: 'post',
    baseURL: userEndpoint,
    headers: {
        common: {
            Accept: 'application/json',
        }
    }
}).then(...).catch(...);
like image 111
Shivam Avatar answered Dec 08 '25 16:12

Shivam