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?
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:-
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With