Home > database >  Possible Unhandled Promise Rejection (id: 0): axios in Redux
Possible Unhandled Promise Rejection (id: 0): axios in Redux

Time:01-22

I am calling an API in action, but it gives me a warning: Possible Unhandled Promise Rejection (id: 0): here is my code: actions.js

import {BASE_URL} from '../Http/config';
import * as Action from './actionTypes';

export const userLoggedIn = ({emphone, pass}) => {
  const formdata = new FormData();
  formdata.append('emphone', emphone);
  formdata.append('pass', pass);
  formdata.append('submit', 'submit');

  try {
    return async dispatch => {
      const res = await axios({
        method: 'POST',
        url: BASE_URL   '/login.php',
        data: formdata, //'emphone','pass','submit
        // body: formdata,
      });
      if (res.data) {
        dispatch({
          type: Action.USER_LOGGED_IN,
          payload: {
            userPhone: formdata.get('emphone'),
            userToken: res.data.response.token,
          },
        });
        console.log(res.data);
      }
    };
  } catch (error) {
    console.log(error);
  }
 };

calling an action in LoginScreen submit handler:

dispatch(userLoggedIn({emphone: '8107224909', pass: 'shub@123'}));

I searched on internet for this warning but I found some solutions but they seems confusing to my implementation. Any help will be appreciated.

CodePudding user response:

You need to move try/catch inside the dispatch function:

 return async dispatch => {
    try {
      const res = await axios({
        method: "POST",
        url: BASE_URL   "/login.php",
        data: formdata, //'emphone','pass','submit
        // body: formdata,
      });
      if (res.data) {
        dispatch({
          type: Action.USER_LOGGED_IN,
          payload: {
            userPhone: formdata.get("emphone"),
            userToken: res.data.response.token,
          },
        });
        console.log(res.data);
      }
    } catch (error) {
      console.log(error);
    }
  };
  •  Tags:  
  • Related