how to log the last search request when autocomplete is in place?

Viewed 377

For example, when a user types android .

A client sends multiple requests to the server namely a an and and so on.

I'd like to log the android search request only in the server.
How can I do that?

I'm thinking of the following strategy, but wonder if there's a better one.

  1. do the autocomplete as before
  2. send the special log this search request if 1 sec has passed after a user pressed keyboard

If I were to implement the above, how would one use redux-saga to do it?

1 Answers

You need to implement debounce in bunch of takeLatest effects. So, if i.e. your component dispatches INPUT_CHANGED action, then your saga will look like:

import { call, takeLatest, delay } from 'redux-saga/effects'

function* handleLog(action) {
  // debounce by 1 sec
  yield delay(1000); 
  if (action.payload.LOG_THIS_SEARCH_REQUEST) {
     const apiResult = yield api.log(action.payload.value);
     ...  // logic after api call is done
  }
}

function* watchInput() {
  // log latest input change
  yield takeLatest('INPUT_CHANGED', handleLog);
}

So, in provided example, if in 1 sec user triggers a new input change (i.e. add one more letter), then saga will handle only latest one.

Related