Reputation: 26034
I'm using React, Redux and react-router. I have a button "Add member" that opens a "new member" form, using react-router.
In the "app container", I have this:
<Switch>
//other stuff
<Route exact path='/addmember' component={ NewMemberForm }/>
</Switch>
and the button:
<Button label='Add member' onClick={ _ => this.props.history.push('/addmember')} />
Form is opened properly. NewMemberForm
component has two buttons: Add
and Cancel
. Cancel
button, basically, does this.props.history.push('/')
to go back to the home page.
When user clicks Add
, form data is read and an async action is dispatched:
//add member using the api and set the generated ID
export const requestAddMember = member => dispatch => {
return api.addMember(member)
.then(memberId => dispatch(
addMember(Object.assign(member, { id: memberId }))));
};
const addMember = member => {
return { type: ADD_MEMBER, member };
};
I need to go back to the home page (this.props.history.push('/')
), when ADD_MEMBER
action is dispatched, i.e. when the new member is actually added.
When do I have to handle that action and call this.props.history.push('/')
? Should it be in the async action creator before dispatch ADD_MEMBER
?
//add member using the api and set the generated ID
export const requestAddMember = member => dispatch => {
return api.addMember(member)
.then(memberId => dispatch( // should it be here before this dispatching?
addMember(Object.assign(member, { id: memberId }))));
};
Upvotes: 4
Views: 1477
Reputation: 26034
I found a working solution.
history.js
import createHistory from 'history/createHashHistory'
export default createHistory()
and in the action creator:
actions.js
import history from './history';
...
//add member using the api and set the generated ID
export const requestAddMember = member => dispatch => {
return api.addMember(member)
.then(memberId => {
history.push('/'); //this line
dispatch(addMember(Object.assign(member, { id: memberId })))
});
};
Upvotes: 1