Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect in axios?

Tags:

reactjs

axios

Can I redirect in .then instead of console.log?

axios
  .post('/api/users/login', user)
  .then(res => console.log(res.data))
  .catch(err => this.setState({ errors: err.response.data }))

Is it possible and if it is how can I do it?

like image 686
Anelia Kostadinova Avatar asked Oct 21 '25 15:10

Anelia Kostadinova


1 Answers

I would suggest that you should not perform side operations inside the actions (in this case axios call). This is because you would eventually add these calls inside redux thunk/saga or some other middleware.

The pattern which I follow is you return the promise and add the redirection logic inside your components(or containers). Following are the benefits of it:-

  1. It makes your code cleaner and avoids side affects inside your API calls.
  2. It makes easier to test your API calls using mock data.
  3. Showing alert in case the API fails without passing callback as function parameter.

Now, that being said you can use the above logic in following ways:-

// Component code

import { browserHistory } from 'react-router';

class TestContainer extends React.Component {
  auth = () => {
    login()
    .then(() => {
      browserHistory.push("/addUser");
    })
    .catch(() => {
      // Show alert to user;
    })
  }
  
  render () {
    return (
      <div>
        <button onClick={this.auth}>Auth</button>
      </div>
    );
  }
}

// Action code 

const login = () => {
  return axios
  .post('/api/users/login', user);
}
like image 102
Harkirat Saluja Avatar answered Oct 23 '25 06:10

Harkirat Saluja



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!