N
N
noneim2017-01-22 00:46:41
JavaScript
noneim, 2017-01-22 00:46:41

Asynchronous request library for react?

If the ajax request for data from the server can be long (2 or more seconds), in modern frameworks like react, you can easily display progressbar, loading icon, etc. But at this time, the user has the right to work with the application further, press various buttons, i.e. start other data loading processes, etc. And so a question - whether there is at present a library which is capable to resolve such chaos in actions of the user?
An example of incorrect possible processing:
1) The client selected filters in the search form, pressed the button, the data is loaded ... then the user selected other filter parameters, pressed the button again - as a result, the second request can theoretically work faster than the first, then the data from the first request will come, as a result - the parameters of the specified the filter user will be from the second request, and the displayed result will be from the first.
2) Resubmitting the form data - there is of course a standard method for blocking the button from being pressed, but it would be desirable to transfer this to the functionality of the library.
Here is an approximate specification for such a library:
Types of processes:
1) Getting additional data (for example, the full text of a blog article)
- If the target component is hidden (go to another tab, close the component, etc.) - then cancel the process.
- If a repeated request for the same data - we ignore such a request.
- We can also cancel the download by pressing a button.
2) Getting the form data with the specified filters at the input (search by parameters for example)
- During loading, we show the filters as they were selected by the user.
- If the target component is hidden, then cancel the process.
- If other filters are set at the input, then we cancel the previous process and create a new one.
- If the download was canceled, then we return the filters to their original state.
+ data can come via websocket
In the general case, this is a kind of finite state machine with rules for any regular / freelance case. Is there something ready now?

Answer the question

In order to leave comments, you need to log in

4 answer(s)
N
Nikita Gushchin, 2017-01-22
@iNikNik

Yes, there is such a library. The problem is that in JS, native promises (Promise) cannot be canceled (not cancelable) ... but at the same time - we have generators that quite allow themselves to simulate the cancellation of the execution of a function, say, in the middle.
In order for everything to work - you need to use a bundle from any library you like for direct requests (I prefer isomorphic-fetch ), then take redux and middleware for it (redux) - redux-saga .
If you are not familiar with the redux ecosystem or if you are hearing about redux-saga for the first time, read the documentation, watch the tutorials. In short - the library is built on generators. The generator function returns an iterator and its execution stops every time we return a new value (yield) to the iterator.

function* myCancelableAction(someData) {
  // вернет итератору промис и приостановит работу функции до следующего вызова next
  // в нашем случае - функция продолжит выполнение, когда придет ответ сервера
  const response = yield doAjaxRequest(someData) 
  yield dispatchSuccessAction(response)
}

const action = myCancelableAction();
const promise = action.next().value // fetch promise

promise.then(response => {
  // если новых запросов не поступило
  if(!newRequestIsComing) {
    // мы можем передать значение в нашу функцию (через next)
    console.log(action.next(response).value); // dispatched action
  }
})

So after the function has returned for the first time, in relation to the topic of the post it will be "make an AJAX request", we can not execute it further (if we want). In this case, it will not be possible to cancel the ajax request, but we can simply ignore its results (not dispatch the success action, for example).
UPD1 updated code example

A
Anton Bobylev, 2017-01-22
@dpigo

Look towards RxJS

I
Ivan, 2017-01-22
@LiguidCool

Well, these are the costs of asynchrony, for which they love and hate JS so much.
I think for the same React or Angular, these are all the occasional programmer who wrote the code. By and large, you cannot block something for the duration of the asynchronous execution. For example, you made a request for data and for this time through the state (I'm talking about React) blocked the button ... And then your AJAX took it and did not return (well, some kind of magic). And a paragraph - press F5.
And by the way, maybe if the server gives the data for so long, then ... Hmm, let it give everything at once, and let the frontend filter. Try it, maybe this is your solution.

M
Maxim, 2017-01-22
@maxfarseer

I also encountered a similar problem, I will describe how it looks in my draft, but in general it has not been nicely resolved yet:
There is a project on the elixir + phoenix backend. I get ref + auto-increment id in every message . Therefore, when I make the first request and the data takes a long time, and then the second request and the data arrives faster, then the ref will be larger and I just ignore the old response in the reducer (in the style, action.ref < state.ref => return the current state) .
PS if you are using sockets, how do you "slow down" getting a response? I had to ask the "backend" to respond more slowly to test this problem. Since in the chrome devtools in the network, "slowdown" did not work for socket requests.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question