React setState: are multiple callbacks synchronized? - javascript

Say there is such a case:
In the state, there is a list, which corresponding to multiple rows in a table on the UI. There are multiple api calls, one for each item (row), which will retrieve the latest status, and update one item in the list.
In such case, I can understand that callback method will be better than direct call of setState. However, I still don't know whether multiple calls of the callback will be synchronized.
For example, whether the following situation will happen?
callback 1 reads list
callback 2 reads list
callback 1 updates list(0)
callback 2 updates list(1)
callback 1 writes back
callback 2 writes back
In such case, the update from 1 might be lost, which is typical for read-modify-write.

I still do not clearly understand your problem, perhaps if you could provide some code it would be better.
But if you meant to call a fetch function multiple times and setting the state once it's arrived, then you should be safe to assume that a setState should not override another, whether were your calls done asynchronously or synchronously.
But in any case, you shouldn't as a front-end send this much requests at once, you should request all the data from the server

Related

Best practice for Redux API concurrent actions

I have an action, reducer, and service for some resource.
Let's assume in this case the resource is a cart, from which a user can have multiple of.
I have the following methods, getCartInformation, getCarts, getCartCount.
And I have the following API's, fetchCartInformation, fetchCarts, fetchCartCount.
getCarts returns the cart id's which are needed for getCartInformation and getCartCount
The question is, what would you do to avoid making multiple fetchCarts calls to the API whenever you call getCartInformation or getCartCount as a side-effect
Would you extend the API library with a fromCache flag, so that fetch*** has that option available.
Would you set a counter on the API library of "calls while querying the endpoint" and then just re-trigger the callers of the functions?
Would you add a check on the action to see if getState has already the cart, and if not query and re-trigger the function (might have 2 or more concurrent calls at the same time for a slow endpoint)?
Let's now assume that multiple components might trigger the getCartCount call, sometimes you want to call the endpoint when the component appears in the page and sometimes they all get called in the initialisation of the app because the components are all being added. In this case this will call the endpoints getCarts and getCartCount quite a couple of times.
Is there some kind of "redux-way" to catch that there's multiple calls to one method before it has already resolved?
Would you set a counter of calls on the getCarts action?
Would you make the action getCartCount depend on the getCarts promise response, and have a check on the getCarts action?
I know it's a bit complex and long question, but if there's more or less detail needed please let me know.
I do not understand why you should call getCarts whenever you call getCartInformation. Common use case is: (1) user see list of cards (by getCards) and (2) user click on one of them and see card info (by getCartInformation with id of selected card). Looks like you do not need to call getCards one more time.
It is usual to divide list of cards into pages. So you always have start, offset, total fields as service fields at every getCards call, so you do not need getCartsCount at all.
When I applied any kind of cache, it was reasonable to me to make it transparent for Redux, i.e. Redux action perform API call in usual way, and API layer decides (under the hood) should it send real ajax call or should it return data from cache.

Subscription in Tracker.autorun causes publish callback to fire multiple times

I'm working in a ReactJS and Meteor project and I found a strange behavior I'm gonna describe here:
There is a Tracker.autorun block with a Meteor.subscribe call inside. So far, so good. In the server side, there is a matching Meteor.publish which declares a callback.
As far as I understand, the Meteor.publish callback should fire once for each subscription received, but somehow this callback is firing 3~4 times for a single subscription.
In my last test the Tracker.autorun block executed 4 times, the subscribe only executed 1 single time and the callback fired 4 times.
The Meteor.subscribe only runs once, even the tracker runs several times. How could it cause the callback to fire more the once?
Does it make sense?
Do you know what could explain such behavior?
If you need any other information, just let me know.
Thanks in advance
Meteor.publish('current-user', function currentUser(credentials) {
return Users.find();
});
Tracker.autorun((c) => {
if (!currentUserHandler) {
currentUserHandler = Meteor.subscribe('current-user', this.credentials);
}
});
You should expect that the autorun will fire twice as a normal condition, once without data, and the second with some data.
That is to allow you to show a "loading" state before the data arrives.
You are subscribing to the users collection, which is a special collection. Meteor uses it for authentication, and also to record session activity. You are doing a Users.find(), which is an unfiltered query on the whole users collection, so any modification to any user will cause it to fire. You also won't be able to see all of the users records (for security reasons).
It's probable that you are storing additional data on the users record, hence the need for you to subscribe to it. I would recommend that you consider storing this data in another collection, such as 'members', 'visitors', 'profiles' or whatever name suits you. Things are likely to work better that way.

jQuery .when().then() not working as expected

I have an object which acts as a client side API Client which exposes several functions which all return jQuery ajax() objects. Some of those ajax calls have .done() and .fail() calls chained directly onto them because they are actions which need to be taken every time the API responses come back before the rest of the js code is allowed to deal with the response. Pretty standard stuff.
I need to kick off a variable number of API requests, wait for all to fail or succeed, and then continue processing. For the examples I will create, I will simplify this down to just two ajax calls.
So I create an array to hold the returned ajax objects, and then use $.when().apply(null, deferreds).then(function(){//do something after both ajax requests complete}). When the calls complete successfully, everything works great. When calls fail (such as if the ajax call 404s), things are not so great.
The problem is that .then() doesn't seem to detect the fails, even though I thought then() was supposed to be fired regardless of success or failure of the underlying promise(s).
I can switch to .always(), which seems to work better (in that it detects the failures and still triggers the callback) but it seems to fire before some of the .fail() callbacks that are registered directly on the ajax calls, which doesn't make sense to me since I thought the callbacks for an ajax call were called in the order they were registered.
I'm sure I'm just missing something about the behavior of the ajax() when() then() combo.
Fiddle showing successful calls using .then(): https://jsfiddle.net/kwrLyw6q/5/
Fiddle using .then() with failed ajax calls (not working, would love to know why. Seems like this is the "right" way to do it, but I can't figure out where I'm going wrong): https://jsfiddle.net/kwrLyw6q/2/
Fiddle using .always() (working, but notice the out-of-order callback order. At least, out of order compared to the order I want them!): https://jsfiddle.net/kwrLyw6q/7/
It looks like deferred.then() takes three arguments:
success function (first argument).
fail function (second argument).
progress function (third)
updated fiddle

how to think about asynchronous callback operations in Node.js

Learnyounode is a commandline based learn-by-doing-and-getting-your-results-tested tutorial for javascript's node
In the seventh tutorial, the idea is to make something of a http client using node.js's http's get function.
The get function has two arguments
the url
a callback function for the asynchronous job
So I scourgd the surface of the internet looking for a way to continously accept data till the operation ended. After a while seeing that every answer was pretty much along the lines of
function callback(res){
res.on("data",function (data) { console.log(data.toString());})
}
http.get(url,callback)
I thought maybe failing the inbuilt tests would give me a clue to see how to make multiple calls but weirdly enough it passed the multiple calls test.So I thought the test called the file and hence the function, multiple times .. but after some tries..I realised that wasn't the case.
So my question : what exactly goes on behind a async call ? how is it possible for the mechanism to call it more than once? What other surprises should I expect ? to me this is taking black box thinking to a whole new level and I place it on par with thinking about list monads atm.
I think the key point is to understand that res is an EventEmitter (IncomingMessage to be more accurate), so what does the function named callback (only once on the response event of the httpClientRequest object you create when calling http.get()) is to attach an event listener to the data event of res. Without going into details, to optimise data flow, when you receive some data bytes from the network a buffer is filled and when is full the event 'data' is triggered so you can process the incoming chunk. Hence the callback you have set to the data event is executed on every chunk of data coming from the network

Issues with having multiple observables firing off multiple times

In Ember.js, I have a Controller property function which calls an json request, and it needs to have multiple observables, as there are multiple conditions where I need to update the json data.
This works great when only one of the properties observed changes, however, when there is a case that multiple properties goes through a change, this is causing the json request to fire off multiple times with the identical request. How can I limit the amount of times that this function fires off to only once?
I kept the question general to have it be applied to other future cases, however, if it is pertinent, the case that I'm using it for is in the case of Pagination, where I need to observe the page index, the page size, the sorted by, and the sort order.
The simplest approach would be to set a flag on the controller when it is about to make the request, clear it when the request completes, and check the flag in the observer to decide whether to generate the ajax request.

Categories