Redux & React Router: Combing dispatch and navigation (history.push)
You can either user react-router-redux (require an initial set up) and dispatch your action from action creators
import { push } from 'react-router-redux'
class PostContainer extends React.Component {
handleSubmit(data) {
return this.props.addPost(data);
}
render() {
return (
<div>
<Post onSubmit={data=> this.handleSubmit(data)}/>
</div>
);
}
}
const mapDispatchToProps = (dispatch) => {
return {
addPost: (data) => {
dispatch(addPost(data)).data.then((result) => {
dispatch(addPostFulfilled(result.data));
//How do you call the following function?
dispatch(push('/posts'));
}).catch((error) => {
dispatch(addPostRejected());
});
},
}
}
export default connect(null, mapDispatchToProps)(PostContainer);
or just pass push as a "done callback".
class PostContainer extends React.Component {
handleSubmit(data, done) {
return this.props.addPost(data, done);
}
render() {
const { push } = this.props.history;
return (
<div>
<Post onSubmit={data=> this.handleSubmit(data, push)}/>
</div>
);
}
}
const mapDispatchToProps = (dispatch) => {
return {
addPost: (data, done) => {
dispatch(addPost(data)).data.then((result) => {
dispatch(addPostFulfilled(result.data));
//How do you call the following function?
done('/posts')
}).catch((error) => {
dispatch(addPostRejected());
});
},
}
}
export default connect(null, mapDispatchToProps)(PostContainer);