4

I'm currently having an issue in our Flux app where a component needs to first fetch the current user, and, if and only if the current user is fetched, fetch that user's notifications using a different Ajax call, as below:

_onCurrentUserChange: function() {
  this.setState(getStateFromStores());
  NotificationsActionCreator.getNotifications();
},

As you can see, I'm trying to dispatch the action to getNotifications after we know the currentUser has changed.

However, Flux doesn't allow for multiple dispatch of actions, and we've decided that all server requests should be dispatched through actions.

Thus, there's no way for me to wait on the currentUser to be received, and then dispatch the action to fetch the notifications.

What would be the correct Flux way to do this?

an1lam
  • 629
  • 8
  • 15

1 Answers1

1

So I figured I'd post the way I fixed this for other people to see.

Basically, we ended up creating a function in our WebApiUtils module that makes sequential Ajax calls to the getCurrentUser and getNotificationsForCurrentUser backend routes. Then, we dispatch an action that contains both the currentUser and the notifications. The currentUser and notification stores both listen for this event, and each grabs the data it requires.

If you want to see the code for this, check out: https://github.com/krazemon/repcoin/blob/master/js/api.js#L16 https://github.com/krazemon/repcoin/blob/master/js/stores/AuthStore.js#L59 https://github.com/krazemon/repcoin/blob/master/js/stores/NotificationsStore.js#L59-L62

I chose this solution because it doesn't violate the synchronous property of our stores and allows us to avoid cascading dispatch.

an1lam
  • 629
  • 8
  • 15
  • I just ran into a similar issue, where I was adding an item (ajax call 1) and then fetch the entire list with all items, including a newly added one (ajax call 2). I decided to also solve this in the api, just like you. Thanks for posting links to the source code. – T. Junghans Mar 01 '15 at 19:48
  • No problem. Glad that this was helpful to you. – an1lam Mar 02 '15 at 18:55