Search code examples
reactjsactionflux

React + Flux: best practice for calling an action after another action?


I have a component, let's call it List, that calls an action creator Action1.getItems(). After Action1.getItems() has retrieved information from a server, I need to call another action creator: Action2.getMoreItems(), which is a totally different action in a different file.

Facts:

  1. Both actions creators dispatch an action and change a store.
  2. I can't call Action2.getMoreItems() inside the _onChange() of List because it throws an error "Cannot dispatch in the middle of a dispatch ..."

Possibilities?

  1. Call Action2.getMoreItems() inside Action1.getItems() after the server returns
  2. Add a callback so I will have Action1.getItems(callback) and call Action2.getMoreItems() inside that callback from List component.

I believe this might be a very basic use of Flux but I still can't get my head around on how to get it right, both solutions look ugly to me.

Suggestions?

Thank you!


Solution

  • Is getMoreItems dependent on the return value of getItems? If so, you can call the action in the .then callback of getItems.

    If it's not, then you can invoke both calls at the same time and then concat the results of the promises.

    So my vote is number 2 in your question. I don't think it's an ugly solution at all. You are delegating the responsibility of getting items and more items to your actions. The component itself is ignorant of that and simply dispatched a request for those items. How they're built should be transparent to the component.