Reputation: 4869
I want to use a result of action which was dispatched and dispatch new action. There an example of code which I want to use
function mapDispatchToProps(dispatch) {
return bindActionCreators({
addApplication(data, vacancy_id) {
dispatch(candidateActions.addCandidate(data))
.then((newCandidate) => {
dispatch(applicationActions.addApplication(data.video, vacancy_id, newCandidate._id))
});
}
}, dispatch);
}
How can I do this in redux and which libraries I can use?
Upvotes: 4
Views: 1676
Reputation: 6606
You should use a thunk-middleware
which will be in charge of dispatching actions based on results of previous action. By using a thunk middleware, an action creator can return a function which is capable of dispatching its own actions.
lets say i have 3 actions:
1. loginRequest - send credentials for login
2. loginSuccess - dispatch action if credentials are valid
3. loginFailure - dispatch action if login failed
i can set up an function which does the below
export function login(credentials){
return function(dispatch){
dispatch(loginRequest(credentials){
return fetch(`http://localhost:8000/login`)
.then(response => response.json())
.then(json =>
dispatch(loginSuccess(creds))
.catch(err =>
dispatch(loginFailure(err))
})
}
}
You can then dispatch the login function from your component by including it in your mapDispatchToProps
You should probably check out - http://redux.js.org/docs/advanced/AsyncActions.html for a better understanding
Upvotes: 4