U
U
Username2018-09-02 21:32:41
JavaScript
Username, 2018-09-02 21:32:41

How to make dynamic data output when data is entered in input?

Hello!
When you enter information into an input field, the value is read and sent to the server via ajax(axios).
The user can enter information faster than the information comes from the server.
How can I write an action that will kill the previous request to the server?
Or is there a better solution without deleting the current request?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-09-03
@rockon404

You can write a simple withLatest helper like this:

export const withLatest = request => {
  let last = 0;

  return (...args) =>
    new Promise((resolve, reject) => {
      const current = ++last;
      request(...args)
        .then(res => resolve({ isLatest: current === last, res }))
        .catch(err => reject({ isLatest: current === last, err }));
    });
};

async/await option
export const withLatest = request => {
  let last = 0;

  return async (...params) => {
    const current = ++last;
    try {
      const res = await request(...params);
      return { isLatest: current === last, res };
    } catch (err) {
      throw { isLatest: current === last, err };
    }
  };
};

Usage:
import Api from '../api';
import { withLatest } from '../utils';

const withLatestFetchData = withLatest(Api.fetchData);

export const fetchData = query => async (dispatch, state) => {
  dispatch({ type: "LOADING_DATA" });
  try {
    const { isLatest, res } = await withLatestFetchData(query);
    if (isLatest) {
      dispatch({ type: "DATA_SUCCESS", payload: res });
    }
  } catch ({ isLatest, err }) {
    if (isLatest) {
      console.log(err);
    }
  }
};

Demo.
I also added debounce to the demo and a small chance that the fake request will end with an error.

C
coderisimo, 2018-09-02
@coderisimo

debounce
https://habr.com/post/60957/
there are ready-made solutions, about them, for example here
https://webdevkin.ru/posts/frontend/kak-ispolzovat...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question