简体   繁体   中英

I am trying to dispatch a action but getting this error: “ Unhandled Rejection (TypeError): Cannot read property 'type' of undefined”

import axios from "axios";

export function login(content) {
  console.log(content);
  return dispatch => {
    axios.post("/v1/login", content).then(res => {
      console.log(res);
      if (res.data.response.userResponse.userResponseCode == 20000) {
        dispatch(loginSuccess(true));
      }
    });
  };
}

function loginSuccess(isLogginSuccess) {
  console.log(isLogginSuccess);
  return {
    type: LOGIN_SUCCESS,
    isLogginSuccess
  };
}

export default function reducer(
  state = {
    isLogginSuccess: false
  },
  action
) {
  switch (action.type) {
    case LOGIN_SUCCESS:
      return {
        ...state,
        isLogginSuccess: action.isLogginSuccess
      };
    default:
      return state;
  }
}

While doing user login I am calling this action. If user successfully logged in, isLogginSuccess will be true. Trying to call action, but getting error.. please anyone help..

Axios returns a promise, which can resolve or reject. In your case it is returning a rejection and your code isn't handling it. Typically you'd catch it and dispatch some failure action, log it, or ignore it, anything else, but you still need to catch the rejected promise.

For example:

export function login(content) {
  console.log(content);
  return dispatch => {
    axios
      .post("/v1/login", content)
      .then(res => {
        console.log(res);
        if (res.data.response.userResponse.userResponseCode === 20000) {
          dispatch(loginSuccess(true));
        }
      })
      .catch(() => {
        dispatch(loginSuccess(false));
      });
  };
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM