1

I'm still beginning in react and redux and now I followed this tutorial and it uses this middleware for dispatch. I was wondering how I would do another dispatch after the first one (to chain it)? I have something like this now.

fetchData() {
  const { dispatch } = this.props;
  const action = PageActions.fetchPage({slug: this.props.params.slug});
  dispatch(action);
}

and wondering if I can dispatch(action).then(...) but the return of dispatch is always undefined. Is that possible?

Clarkie
  • 7,490
  • 9
  • 39
  • 53
index
  • 3,697
  • 7
  • 36
  • 55
  • Yes, it's possible. It's solved [here](https://stackoverflow.com/questions/50208749/why-dont-chaining-dispatch-redux-thunk) – mrkacan May 07 '18 at 07:36

1 Answers1

3

If you would like to use async actions inside of your action creators you need to use middleware. The recommended middleware is thunk.

There is a good post on Stack about it's usage and appropriate situations. Stack Overflow Async Actions

This will allow you to dispatch many actions from a single action. However if you are wanting to "chain" actions together you should simply dispatch the second action at the end of the first actions definition.

ie

function getBookings() {
  return (
    RequestHelper.fetchEntities(Routes.bookings.all, {}, queryParams)
      .then(res => dispatch(getBookingsSuccess(res));
  )
}

...
function getBookingsSuccess(data) {
  dispatch(showSuccess());
}
Community
  • 1
  • 1
JamesWatling
  • 1,175
  • 1
  • 9
  • 17
  • If I do use `redux-thunk`, do I need to remove my existing promiseMiddleware? If I don't, how should I chain the next one in my action creators? Adding `.then` to my usual actions doesn't work eg. `return { type: FETCH, promise: request.get(...)[.then(...)]}`. Both does do the request I can see on the server but my app fails though. – index Apr 07 '16 at 04:37
  • 2
    So I used and learened thunk to accomplish this. Thanks! – index Apr 14 '16 at 05:53