Tracking ajax request status in a Flux application - reactjs-flux

We're refactoring a large Backbone application to use Flux to help solve some tight coupling and event / data flow issues. However, we haven't yet figured out how to handle cases where we need to know the status of a specific ajax request
When a controller component requests some data from a flux store, and that data has not yet been loaded, we trigger an ajax request to fetch the data. We dispatch one action when the request is initiated, and another on success or failure.
This is sufficient to load the correct data, and update the stores once the data has been loaded. But, we have some cases where we need to know whether a certain ajax request is pending or completed - sometimes just to display a spinner in one or more views, or sometimes to block other actions until the data is loaded.
Are there any patterns that people are using for this sort of behavior in flux/react apps? here are a few approaches I've considered:
Have a 'request status' store that knows whether there is a pending, completed, or failed request of any type. This works well for simple cases like 'is there a pending request for workout data', but becomes complicated if we want to get more granular 'is there a pending request for workout id 123'
Have all of the stores track whether the relevant data requests are pending or not, and return that status data as part of the store api - i.e. WorkoutStore.getWorkout would return something like { status: 'pending', data: {} }. The problem with this approach is that it seems like this sort of state shouldn't be mixed in with the domain data as it's really a separate concern. Also, now every consumer of the workout store api needs to handle this 'response with status' instead of just the relevant domain data
Ignore request status - either the data is there and the controller/view act on it, or the data isn't there and the controller/view don't act on it. Simpler, but probably not sufficient for our purposes

The solutions to this problem vary quite a bit based on the needs of the application, and I can't say that I know of a one-size-fits-all solution.
Often, #3 is fine, and your React components simply decide whether to show a spinner based on whether a prop is null.
When you need better tracking of requests, you may need this tracking at the level of the request itself, or you might instead need this at the level of the data that is being updated. These are two different needs that require similar, but slightly different approaches. Both solutions use a client-side id to track the request, like you have described in #1.
If the component that calls the action creator needs to know the state of the request, you create a requestID and hang on to that in this.state. Later, the component will examine a collection of requests passed down through props to see if the requestID is present as a key. If so, it can read the request status there, and clear the state. A RequestStore sounds like a fine place to store and manage that state.
However, if you need to know the status of the request at the level of a particular record, one way to manage this is to have your records in the store hold on to both a clientID and a more canonical (server-side) id. This way you can create the clientID as part of an optimistic update, and when the response comes back from the server, you can clear the clientID.
Another solution that we've been using on a few projects at Facebook is to create an action queue as an adjunct to the store. The action queue is a second storage area. All of your getters draw from both the store itself and the data in the action queue. So your optimistic updates don't actually update the store until the response comes back from the server.

Related

How to distinguish two responses that have the same status code but different response body?

I have an application where users can take part of puzzle solving events. I have an API endpoint /events/{id} that is used to get data associated to a certain event.
Based on whether the event has ended, the response will differ:
If the event has ended, the endpoint will return event name, participants, scores etc. with status code 200
If the event has not ended, the endpoint will return event name, start time, end time, puzzles etc. with status code 200.
On the client-side, what is the best way to distinguish these two responses from each other to decide which page to display, results page or event page? Is this a good way to accomplish my goal?
Some might answer that I should already know on the client-side whether the event has ended and then query for data accordingly. But what if user uses the address bar to navigate to an event? Then I will have no data to know, whether it truly has ended. I wouldn't like to first make an API call to know that it has (not) ended and then make another one for results/puzzles.
pass a boolean isFinished and return it inside of response object. If your response object is already defined, create a wrapper that has the previous response dto and a boolean flag.
Also we did use a solution like this in one of our projects at work for a big company so I would say it is somewhat industry accepted way of doing it.

Best way to handle ajax request in Flux?

I'm thinking about Flux architecture of React and I want to identify the best way of handling Ajax requests. See the example of a comment box in below picture.
The overall architecture is clear, my concern is: should we really need a separate store for saving a view's private state such as Ajax request is failed?
Why we have stores is because data could be reused by different views. But should a network result also reused for other views besides the view originates the request?
Whether the ajax request success or fail is also a state of the view such as setState({loading: true/false}). And this state is not related with the data result of the request. The private loading state may be related with different network requests such as post, refresh, delete etc. I know some people suggests to provide a ErrorStore for this scenario. But if we don't develop stateless component I can't see any reason we only save network state in a separate store.
So in my project I use Promise:
actionCreators.postComment({...})
.then(res => this.setState({loading: false, error: null}))
.catch(err => this.setState({loading: false, error: err}));
The above code corresponds to the red part of the picture.
So my question is: is this approach reasonable? Or does Redux/Reflux have better ways? Thanks.
I don't see an issue with storing the ajax request state in your store - you don't need a separate store just for that. You can keep the state within your view store.
In your diagram, where you have the condition "Success?", it can dispatch a success or failure action and the store can save the fact that the request was a success (you may wish to have some sort of non-blocking UI which disappears when this is successful).
A request may fail because of a model validation error, not just a network failure. In this case, it would be worthwhile storing these errors into the store, there's no harm in it.
One of the benefits of the Flux architecture is that there's single, defined flow of data, however in your diagram the flow of data is conditional depending on the success of ajax requests. If you keep request states within your store, sent via dispatches, then you will maintain that single flow of data.

AngularJs - Persistence, storage, ajax requests, data integrity

I'm evaluating whether AngularJS will work as a solution for my moderately simple web application.
The aim is to cut down the amount of AJAX server requests for data as much as possible.
My actual question is simple, yet the repercussions of that request is leading to confusion.
In a nutshell: "Can Angular modify parts of JSON data received from a backend through user input and maintain state until I'm ready to return that data.
Scenario:
Grab JSON data from the server that contains a root name & associated address details for each root name. The list is rendered to screen along with an 'Edit Address' button for each item.
The user clicks 'Edit Address', Angular displays a form with the address data for the root name.
The user edits the data, clicks submit, the client sends JSON data to the server and, for arguments sake, we get a success return. The address details are modified.
This is where the meat of my question - and lack of understanding - comes to the fore.
Do I need to get the entire list of 10 items back from the server with the single modified address details, just from editing a single list item OR can I simply update that single item client side and hold state as the user returns to the list, say, to edit another item?
IOW, we get a success, but no data is actually returned aside from 'success' - our client has stored the changes.
This is where the data integrity issue rears it's ugly head.
** OR **
Grab a list of root items without associated address data.
The user clicks on an 'Edit Address' button for the root item.
We fetch the address data for the root name from the server and the form is displayed, the user edits the data, submits, send data asynchronously, get a success.
User returns to the list and another server request is made to grab the list from the server again.
This is hellishly difficult to explain, but the bottom line is about persistence and data integrity.
Is it best practice to make a server requests after each user edit of data, or can modified data be stored client side - with persistence?
obviously validation will be done server side, as well as client side.
What you're asking is more of a server-side question, on how to design a good RESTful API that allows changes to individual entities without sending/loading the entire list each time. So the answer to your question is that it's entirely up to you... angular does a great job of binding UI elements to the javascript objects in your controllers for you, but when it comes time to save that data to the server, you can do it however you want.
In an ideal world (IMO) your server-side API would support the following:
Get a list of addresses (angular stores them in $scope.addresses)
Get a single address
PUT/PATCH to update an address (when a user makes a change to a single address and confirms it) and return 204 no content
POST to create new addresses, and return the created address with a server-provided identifier (like "id"), that you can use in angular to determine whether an address has been persisted server-side or not. After POSTing, you rewrite the angular scope object with what you got from the server to save the id field.
DELETE to remove them (returning nothing)
With this, when you have the client create an address, you should send a POST to the server to create one, take the response JSON and copy it over the object you just saved, so that now it has an "id" field (or similar). You can use angular templates to visually represent that anything with an "id" field is saved to the server. This way you don't have to re-grab the whole list every time you save.
For updating addresses, this is why PATCH is useful: you can send only the changes to individual fields to the server and ensure that only things the user has changed get sent.
Deleting addresses can work by checking if the "id" field is there, and if so, send a DELETE to the server, and if not, the object was never "saved", so just remove the address from the scope. Upon successful deletion you can just remove the address from the scope, no need to reload everything.
When it comes to the "data integrity", ie. if there's other addresses created since you've done the original data request, you'll have to do this on your own... Ideally similarly to how Stack Overflow or Github does it, which is to hint in the UI that there has been server-side changes and you should click to refresh. How to determine refreshes is up to you, but you can keep it simple with polling at intervals, or you can go all out and do WebSockets/Server-side events and actually push changes to the browser.
The best way to create UIs that persist to the server is a complicated topic and there are a lot of best practices. Angular will support whatever you want, but you need coordination on the server to do it.

How to deal with out-of-sequence Ajax requests?

What is the best way deal with out-of-sequence Ajax requests (preferably using a jQuery)?
For example, an Ajax request is sent from the user's browser anytime a field changes. A user may change dog_name to "Fluffy", but a moment later, she changes it to "Spot". The first request is delayed for whatever reason, so it arrives at the server after the second, and her dog ends up being called "Fluffy" instead of "Spot".
I could pass along a client-side timestamp along with each request, and have the server track it as part of each Dog record and disregard earlier requests to change the same field (but only if there is a difference of less than 5 minutes, in case the user changes the time on her machine).
Is this approach sufficiently robust, or is there a better, more standardized approach?
EDIT:
Matt made a great point in his comment. It's much better to serialize requests to change the same field, so is there a standard way of implementing Ajax request queues?
EDIT #2
In response to #cherouvim's comment, I don't think I'd have to lock the form. The field changes to reflect the user's change, a change request is placed into the queue. If a request to change the same field is waiting in the queue, delete that old request. 2 things I still would have to address:
Placing a request into the queue is an asynchronous task. I could have the callback handler from the previous Ajax request send the next request in the queue. Javascript code isn't multi-threaded (or... is it?)
If a request fails, I would need the user interface to reflect the state of the last successful request. So, if the user changes the dog's name to "Spot" and the Ajax request fails, the field would have to be set back to "Fluffy" (the last value successfully committed).
What issues am I missing?
First of all you need to serialize server side processing for each client. If you are programming in Java then synchronizing execution on the http session object is sufficient. Serializing will help in case the second update comes while the first is being processed.
A second enhancement you can implement in your entity updating is http://en.wikipedia.org/wiki/Optimistic_concurrency_control. You add a version property (and column) for your entity. Each time an update happens this is incremented once. In fact the update statement looks like:
update ... set version=6 ... where id=? and version=5;
If affected rows from above pseudoquery query are 0 then someone else has managed to update the entity first. What you do then is up to you. Note that you need to be rendering the version on the html update form of the entity as a hidden parameter and sending it back to the server each time you update. On return you have to write back the updated version.
Generally the first enhancement would be enough. The second one will improve the system in case many people are editing the same entities at the same time. It solves the "lost update" problem.
I would implement a queue on the client side with chaining of successful requests or rollbacks on unsuccessful requests.
You need to define "unsuccessful", be it a timeout or a returned value.

Best practice for combining requests with possible different return types

Background
I'm working on a web application utilizing AJAX to fetch content/data and what have you - nothing out of the ordinary.
On the server-side certain events can happen that the client-side JavaScript framework needs to be notified about and vice versa. These events are not always related to the users immediate actions. It is not an option to wait for the next page refresh to include them in the document or to stick them in some hidden fields because the user might never submit a form.
Right now it is design in such a way that events to and from the server are riding a long with the users requests. For instance if the user clicks a 'view details' link this would fire a request to the server to fetch some HTML or JSON with details about the clicked item. Along with this request or rather the response, a server-side (invoked) event will return with the content.
Question/issue 1:
I'm unsure how to control the queue of events going to the server. They can ride along with user invoked events, but what if these does not occur, the events will get lost. I imagine having a timer setup up to send these events to the server in the case the user does not perform some action. What do you think?
Question/issue 2:
With regards to the responds, some being requested as HTML some as JSON it is a bit tricky as I would have to somehow wrap al this data for allow for both formalized (and unrelated) events and perhaps HTML content, depending on the request, to return to the client. Any suggestions? anything I should be away about, for instance returning HTML content wrapped in a JSON bundle?
Update:
Do you know of any framework that uses an approach like this, that I can look at for inspiration (that is a framework that wraps events/requests in a package along with data)?
I am tackling a similar problem to yours at the moment. On your first question, I was thinking of implementing some sort of timer on the client side that makes an asycnhronous call for the content on expiry.
On your second question, I normaly just return JSON representing the data I need, and then present it by manipulating the Document model. I prefer to keep things consistent.
As for best practices, I cant say for sure that what I am doing is or complies to any best practice, but it works for our present requirement.
You might want to also consider the performance impact of having multiple clients making asynchrounous calls to your web server at regular intervals.

Resources