Sometimes, we want to redirect to a different page with React Router after a Redux action is complete.
In this article, we’ll look at how to to redirect to a different page with React Router after a Redux action is complete.
React Router Redirect after Redux Action
We can redirect after a Redux action is committed.
To do that, we install the history package.
We install it by running:
npm install --save history
Then we can create a function like:
import { createBrowserHistory } from 'history';
const browserHistory = createBrowserHistory();
const actionName = () => (dispatch) => {
axios
.post('url', { body })
.then(response => {
dispatch({
type: ACTION_TYPE_NAME,
payload: payload
});
browserHistory.push('/foo');
})
.catch(err => {
// Process error code
});
});
};
We make a POST request with Axios.
Then in the then callback, we call dispatch to dispatch our actions.
And then we call browserHistory.push to navigate.
We called createBrowserHistory to get the browserHistory object.
Conclusion
We can redirect after a Redux action is committed.