Let's say I have a Link
that sends me to a page for adding/editing a list entry.
How do I dispatch a Redux action when I click on the Link
itself so that I can update the Redux store first, before actually getting redirected to that page.
Eg:
I click on Edit button -> Action is dispatched -> Store updated, {'state': 'edit-mode'}
-> Proceed to redirect.
Or do you have another way in mind to accomplish what I'm trying to do?
Maybe when component has mounted, then I will run an action like stateToEdit
based on certain conditions? If so, then please show to me your way. Thanks
PS: I'm using only one component for all add/edit/delete. So I'm thinking of a way to render based on the state
whether its on edit-mode
or delete-mode
etc.
To set an onClick listener on a link in React:Set the onClick prop on the link. The function you pass to the prop will get called every time the link is clicked.
To add the link in the menu, use the <NavLink /> component by react-router-dom . The NavLink component provides a declarative way to navigate around the application. It is similar to the Link component, except it can apply an active style to the link if it is active.
To navigate to the courses route, we will use the history. push method of the useHistory object. We will add an event handler “onClick” for our button component and define a function “coursesPage ” that handles the click event. The coursesPage function enables us to redirect to another route on clicking the button.
Here are a couple ways you could go about addressing this issue:
Link
, try utilizing browserHistory.push(path)
with an onClick
function.
onClick
, you can dispatch
your action, then push
to a new location.redux-thunk
, which provides a generic way of performing multiple "actions" (be it calling a Redux action, or performing an async operation, or both!) in response to a change.
redux-thunk
actually offers: Can I dispatch multiple actions without Redux Thunk middleware?
incrementTwice
function, imagine just replacing one of the dispatch(increment)
calls with a call to browserHistory.push(action.path)
, similar to the below:Redux thunk action
export const dispatchThenRoute = (myAction, myPath) => {
return (dispatch) => {
dispatch(myAction)
browserHistory.push(myPath);
}
};
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