2
votes

I send data to API with email and password. API Ruby on Rails with library devise-token-auth


signinform.js

......................................................

onSubmit(e){
e.preventDefault();
this.setState({errors: {}, isLoading: true});
this.props.userSignInRequest(this.state).then(
  () => {console.log('ok!')},
  ({resp}) => { console.log(resp.errors); }
);

} .........................................................

actions/signInActions.js

import axios from 'axios';

export function userSignInRequest(userData){
  return dispatch => {
    return axios.post('/auth/sign_in', userData);
  }
}

If email or password are incorrect i get response:

{"errors":["Invalid login credentials. Please try again."]}

But console.log(resp.errors); display undefined. If i put (resp) => { console.log(resp); } I get in console:

Error: Request failed with status code 401 at createError (createError.js?16d0:16) at settle (settle.js?db52:18) at XMLHttpRequest.handleLoad (xhr.js?ec6c:77)

How me get errors in console.log(resp);

1

1 Answers

3
votes

That is because the way you have written resp in argument. You have written resp in bracket like {resp}. It means whenever any object will be passed to this function, resp will be equal to resp property of that object. But as the response only have errors property and no resp property, it shows undefined.

So to work with this you can do either

onSubmit(e){
e.preventDefault();
this.setState({errors: {}, isLoading: true});
this.props.userSignInRequest(this.state).then(
  () => {console.log('ok!')},
  (resp) => { console.log(resp.errors); }
);

or

onSubmit(e){
e.preventDefault();
this.setState({errors: {}, isLoading: true});
this.props.userSignInRequest(this.state).then(
  () => {console.log('ok!')},
  ({errors}) => { console.log(errors); }
);

EDIT:

this.props.userSignInRequest(this.state).then(() =>{
    console.log('ok!')
}).catch((resp) => {
    console.log(resp.response.data);
}));