Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ntamvl/350905a47c0e860eaa512a749d857a20 to your computer and use it in GitHub Desktop.
Save ntamvl/350905a47c0e860eaa512a749d857a20 to your computer and use it in GitHub Desktop.
[Redux Saga] Deduplicate request

How to avoid duplicate API requests with Redux-Saga?

Also it might be a good to decouple your saga from the state shape itself, im alway trying to do this, unless it would provide to copying reducers' logic in your sagas.

You could create a higher order saga for this, which would look something like this:

function* takeOneAndBlock(pattern, worker, ...args) {
  const task = yield fork(function* () {
    while (true) {
      const action = yield take(pattern)
      yield call(worker, ...args, action)
    }
  })
  return task
}

and use it like this:

function* fetchRequest() {
  try {
    yield put({ type: 'FETCH_START' });
    const data = yield call(api.fetch);
    yield put({ type: 'FETCH_SUCCESS', data });
  } catch (err) {
    yield put({ type: 'FETCH_FAILURE' });
  }
}

yield takeOneAndBlock('FETCH_REQUEST', fetchRequest)

In my opinion this way is far way more elegant and also its behaviour can be easily customized depending on your needs.

source: redux-saga/redux-saga#830

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment