T. Junghans
T. Junghans

Reputation: 11683

How and where does updating and retrieving of data happen in the FLUX pattern?

I have been pondering about this for a while now and been unsuccessful in finding any information on the topic of subsequent api (ajax) requests.

Let's say we have list of users and one of them is updated. After updating the user, I would like to retrieve the entire, updated list of users.

My question regards two actions:

  1. Update user
  2. Retrieve all users

It is clear to me, that the React component initiates the view action to update the user resulting in an API request via the dispatcher. What isn't clear to me is where the second request to retrieve the users happens.

Looking at Facebook's Chat example...

Currently I would do this in the API but I would like to know if there are any tested pattern for solving this problem.

Upvotes: 2

Views: 200

Answers (1)

fisherwebdev
fisherwebdev

Reputation: 12690

You don't need two actions doing two XHR calls. You actually want just one action that results in two XHR calls. Beware of the tendency to think that you should cause a cascade of actions -- this is exactly the anti-pattern that Flux was created to avoid.

The side effect of updating the entire list of users should be something the UserStore is doing in response to the USER_UPDATED action.

The UserStore will update the user record. This can happen either optimistically or after the server call completes. The XHR call to update the user server-side can happen either within the updateUser() action creator or within the store. However, you will need to create actions for the success/error of that call, so that the store can respond appropriately.

The next step, again, can happen either optimistically or after you get the data back from the server. The store, in this case, would make a XHR call to retrieve the list of users to update all the relevant records it holds.

But like the last XHR, you will want to create two new actions based on success or error of this second XHR.

Creating new actions keeps your application very flexible and resilient. So that if any other store ever needs to know about the result of these XHRs, it will already be receiving that data.

I'd be remiss if I didn't mention that, if you have control over the server-side code, you should simply build an end point to update the user and return the new list of users -- this would make the client side code much simpler and the entire thing would be more efficient.

Upvotes: 1

Related Questions