Home How can I cleanly perform a sync operation after the completion of an async thunk

# How can I cleanly perform a sync operation after the completion of an async thunk

1252748
1#
1252748 Published in 2018-01-12 17:09:28Z
 Within a react component, I would like to dispatch an asynchronous action, then when it is complete, dispatch a synchronous action that depends on values added by the asynchronous action. Using redux-thunk, so far, I have: /* actionCreators.js */ export function refresh() { return function(dispatch) { return services.getData().then(response => { return new Promise(resolve => { dispatch(addData(response.data)) resolve() }) }) } } /* myComponent.js */ refreshData = id => { this.props.dispatch(refresh(id)).then(() => { this.props.handleChange(id) }) }  This is actually working, but it seems like a lot of nested code, and I am wondering if there is a more standard way to juggle this async.
casieber
2#
 Your overall strategy on performing logic after an async action completes is correct, you need to return a promise from the thunk and then use then() elsewhere to hook into the completion. That said, the first change you can make to help slim down the code is related to the Promise constructor. You can change the refresh() implementation into export function refresh() { return function(dispatch) { return services.getData().then(response => { return dispatch(addData(response.data)); } } }  This is because the type of .then() on a Promise is then(callback: T => S): Promise, meaning that the outcome of calling then is another promise, so there is no need for you to construct your own. Further, it looks like you are mixing both the standard function syntax with the fat arrow (=>) syntax, when being consistent and using => everywhere can also help slim down your code: export const refresh = () => dispatch => services.getData() .then(response => dispatch(addData(response.data)); /* myComponent.js */ refreshData = id => this.props.dispatch(refresh(id)) .then(() => this.props.handleChange(id));