Issue
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?
Solution
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:-
- It makes your code cleaner and avoids side affects inside your API calls.
- It makes easier to test your API calls using mock data.
- 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);
}
Answered By - Harkirat Saluja Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.