Reputation: 649
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?
Upvotes: 4
Views: 708
Reputation: 649
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.
Upvotes: 1