I have a pretty simple set of react components:
container
that hooks into redux and handles the actions, store subscriptions, etclist
which displays a list of my itemsnew
which is a form to add a new item to the listI have some react-router routes as follows:
<Route name='products' path='products' handler={ProductsContainer}> <Route name='productNew' path='new' handler={ProductNew} /> <DefaultRoute handler={ProductsList} /> </Route>
so that either the list
or the form
are shown but not both.
What I'd like to do is to have the application re-route back to the list once a new item has been successfully added.
My solution so far is to have a .then()
after the async dispatch
:
dispatch(actions.addProduct(product) .then(this.transitionTo('products')) )
Is this the correct way to do this or should I fire another action somehow to trigger the route change?
We can redirect after a Redux action is committed. To do that, we install the history package. Then we can create a function like: import { createBrowserHistory } from 'history'; const browserHistory = createBrowserHistory(); const actionName = () => (dispatch) => { axios .
To redirect to another page on button click in React: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function, passing it the path - navigate('/about') . The navigate() function lets us navigate programmatically.
By default, Redux's actions are dispatched synchronously, which is a problem for any non-trivial app that needs to communicate with an external API or perform side effects. Redux also allows for middleware that sits between an action being dispatched and the action reaching the reducers.
To redirect on form submit using React Router: Use the useNavigate() hook, e.g. const navigate = useNavigate(); . Call the navigate() function passing it the path - navigate('/contacts') . The navigate() function lets us navigate programmatically.
If you don't want to use a more complete solution like Redux Router, you can use Redux History Transitions which lets you write code like this:
export function login() { return { type: LOGGED_IN, payload: { userId: 123 } meta: { transition: (state, action) => ({ path: `/logged-in/${action.payload.userId}`, query: { some: 'queryParam' }, state: { some: 'state' } }) } }; }
This is similar to what you suggested but a tiny bit more sophisticated. It still uses the same history library under the hood so it's compatible with React Router.
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