Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch status = cancelled in axios?

I am currently running 2 servers:

  1. To serve the view using react which retrieves data from REST API built with express.
  2. To provide the REST API for the view.

Below is my action for logging a user in:

// Redux Action
export function loginUser(creds, role) {

  return dispatch => {
    // We dispatch requestLogin to kickoff the call to the API
    dispatch(requestLogin(creds));

    return axios.post(`${ROOT_URL}/login/${role}`, creds).then((response) => {
        console.log(response);

        if(response.status === 200) {
          // If login was successful, set the token in local storage
          localStorage.setItem('id_token', response.data);

          // Dispatch the success action
          dispatch(receiveLogin(response));

          return response;
        }
      }).catch(err => {
        // If there was a problem, we want to
        // dispatch the error condition
        dispatch(loginError(err.data));

        return err;
      });
  };
}

I purposely disconnected my database to catch errors and see what happens. So, this is what I can see in the terminal:

12:49:24 Project-0 Server is listening at port 3000
12:49:24 Project-0 Mongoose disconnected
12:49:24 Project-0 Mongoose connection error: MongoError: connect ECONNREFUSED 192.168.1.116:27017
12:49:34 Project-0 Wed, 13 Apr 2016 07:19:34 GMT express deprecated res.send(status): Use res.sendStatus(status) instead at app/index.js:61:7
12:49:34 Project-0 OPTIONS /login/admin Wed, 13 Apr 2016 07:19:34 GMT ::ffff:192.168.1.134 200 5.894
12:49:35 Project-0 POST /login/admin Wed, 13 Apr 2016 07:19:35 GMT ::ffff:192.168.1.134 - -

Now, when I submit the login form, status goes from pending to cancelled.

How can we catch this status using axios or do we have to write a mechanism for this in express itself?

Axios 0.10.0

Note: I couldn't tag axios as the tag doesn't exist and I can't create a new one.

like image 390
shet_tayyy Avatar asked Apr 13 '16 07:04

shet_tayyy


Video Answer


2 Answers

use axios.isCancel()

.catch(err => { 
      if(axios.isCancel(err)) {
        // do something
      }
   }
)
like image 197
Rafał Rowiński Avatar answered Sep 19 '22 01:09

Rafał Rowiński


You actually catch errors(unsuccessful responses) in catch statement. You can for example log it to console like this:

.catch(err => {
        // If there was a problem, we want to
        // dispatch the error condition
        dispatch(loginError(err.data));
        console.log(err);
        return err;
      });
like image 40
Alex Alexeev Avatar answered Sep 22 '22 01:09

Alex Alexeev