A
A
AlexKindGeek2018-06-20 17:07:51
React
AlexKindGeek, 2018-06-20 17:07:51

How to queue requests?

Hello. I have an input, a handler is attached to it

handleChange = (e) => {
    getExercises('exercises', 'exercises', e.target.value, null).then(list => console.log(list));
};

export const getExercises = (domenKey, apiKey, text, next_page, per_page) => {
  const domenPath = domen[domenKey],
        apiPath   = api[apiKey];

  let url = next_page ?
    `${domenPath}${apiPath}?current_page=${next_page}&page=${next_page}` :
    `${domenPath}${apiPath}?current_page=1`;
  url = per_page ?
    `${url}&per_page=${per_page}` :
    `${url}`;
  url = text ?
    `${url}&search=${text}` :
    `${url}`;
  return  Api.get(url).then(({data}) => data.data);
};

That is, as soon as we enter a value into the input, we immediately send a request.
Everything is fine, BUT when we enter 10 into the input immediately, for example, the response first returned an object that matched 10, and then the one that coincided with 1. Because of this, my data is rendered incorrectly.
5b2a5f6535237867089941.png
I so understood - that that request was fulfilled faster. How can this problem be solved?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-06-20
@AlexKindGeek

You can use debounce to solve your problem :

handleChange = e => {
  // handler
};
handleChangeDebounced = debounce(handleChange, 300);

If you use the lodash library , then there is a debounce implementation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question