redux-saga take with regular expression
Asked Answered
T

3

10

I'm making use of redux-saga for my web app, however I've hit a point where I want to be able to create a single saga that handles multiple different request types. In order to do this I want to be able to use take or takeEvery with a reg-ex. For example:

'foo/SOME_REQUEST'
'bar/SOME_REQUEST'
'baz/SOME_REQUEST'

Should all be handled through something like so:

yield takeEvery('*/SOME_REQUEST', handler);

Does anyone know if this is possible or how it can be achieved?

Teressaterete answered 19/6, 2016 at 14:33 Comment(1)
Looking at the source (github.com/yelouafi/redux-saga/blob/master/src/internal/…) it looks as though the matcher can be a function, so you should be able to yield takeEvery(predicateFn, handler);Freeborn
V
2

Here is an example code for that.

Demo: http://kuy.github.io/redux-saga-examples/takex.html
GitHub: https://github.com/kuy/redux-saga-examples/tree/master/takex

Vittle answered 22/6, 2016 at 8:27 Comment(0)
C
12

You can use

yield takeLatest( action => /SOME_REQUEST$/.test(action.type), handler)

or

yield take( action => /SOME_REQUEST$/.test(action.type))

as pointed out here by @lukehedger: github issue

Check the doc: take(pattern)

Cranial answered 19/10, 2016 at 11:16 Comment(0)
V
2

Here is an example code for that.

Demo: http://kuy.github.io/redux-saga-examples/takex.html
GitHub: https://github.com/kuy/redux-saga-examples/tree/master/takex

Vittle answered 22/6, 2016 at 8:27 Comment(0)
S
1

You'll need to use a custom effect.

 //effect.js
    
 export const takeEveryRegex = (pattern, saga, ...args) =>
  fork(function* () {
    while (true) {
      const action = yield take("*")
      if (pattern.test(action.type)) {
        yield fork(saga, ...args.concat(action))
      }
    }
  })

Then in your saga, use it according to normal patterns.

//saga.js    

function* formFailureSaga({ payload, action }) {
  yield console.log("form failure SAGA", payload, action)
}
    
export function* watchFormFailureSaga() {
  yield takeEveryRegex(/^FAILURE[/s/S]*((?=.*FORM))/, formFailureSaga)
}
Sheep answered 8/4, 2021 at 3:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.