V
V
Vika Marmeladka2021-09-23 15:37:53
AJAX
Vika Marmeladka, 2021-09-23 15:37:53

How to repeat beforeSend method from jQuery Ajax in pure JS?

jQuery Ajax has a beforeSend method that allows you to manipulate the home while any data is being sent. React also has a useState hook that, if it has asynchronous calls, it throws isLoading at the time it makes a back request. So how can this be done in pure JS?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
W
WapSter, 2021-09-23
@wapster92

You just change the state before the request and return it after receiving the response.

const getFn = async () => {
  let loading = true;
  try {
    // Некий проммис
  } catch (e) {
    // Обработка ошибки
  } finaly {
    loading = false;
  }
}

Accordingly, instead of loading, you can use anything. And it is not necessary to insert into the finaly, you can already process some code in the error, depending on the result of the request, do something. Showed a common example

A
Alexander, 2021-09-23
@Aleksandr-JS-Developer

JS can't check if the network request is currently sent.
Therefore, there is no such "time while there is a request".
But you can, as mentioned above, first set the state to loading, then send the request.
Now, while the request is in progress, you can show something to the user.
Then, when the answer came (correct or not), change the status from loading to loaded, for example.
When I wrote this, I had the status field in the state, which took four values ​​- 'did_not_load', 'loading', 'loaded_ok', 'loaded_error'.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question