Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
118
rated 0 times [  119] [ 1]  / answers: 1 / hits: 18310  / 8 Years ago, thu, july 14, 2016, 12:00:00

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.


More From » reactjs

 Answers
2

Here are a couple ways you could go about addressing this issue:




  1. Instead of using Link, try utilizing browserHistory.push(path) with an onClick function.


    • Inside the onClick, you can dispatch your action, then push to a new location.

    • However, if you want to perform this series of actions in various components, you will probably suffer from code duplication.


  2. A more robust way to address this issue would be to implement 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.


    • Dan has a great response here highlighting the simplicity of what redux-thunk actually offers: Can I dispatch multiple actions without Redux Thunk middleware?

    • In your case, in the 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);
}
};

[#61371] Wednesday, July 13, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kalaveronicab

Total Points: 3
Total Questions: 100
Total Answers: 105

Location: Guam
Member since Fri, Jun 18, 2021
3 Years ago
;