christoffee
christoffee

Reputation: 693

How do I create a leading debounce with redux-saga

Is there a way to do a leading debounce?

The example on the recipes only shows a trailing debounce. So below is trailing debounce example where we delay the logic fro 500ms:

import { call, cancel, fork, take, delay } from 'redux-saga/effects'

function* handleInput(input) {
  // debounce by 500ms
  yield delay(500)
  ...
}

function* watchInput() {
  let task
  while (true) {
    const { input } = yield take('INPUT_CHANGED')
    if (task) {
      yield cancel(task)
    }
    task = yield fork(handleInput, input)
  }
}

where as i'd like to execute logic on the first call that cancel any subsequent calls until 500ms has ended.

Edit

This can be done by using takeLeading then delaying the saga at the end by however long you want to debounce for.

Upvotes: 6

Views: 2200

Answers (1)

christoffee
christoffee

Reputation: 693

This can be done by using takeLeading then delaying the saga at the end by however long you want to debounce for.

Upvotes: 5

Related Questions