You can not make API calls (or any other side effects) inside the reducers. For that you must use middleware. Redux Saga is one such middleware, which is good for
Redux Saga uses Generator functions, an ES6 feature.
With ES6 generators, we have a different kind of function, which may be paused in the middle, one or many times, and resumed later, allowing other code to run during these paused periods.
*
, e.g. function* foo() {}
yield
keyword, from inside the function1function* foo () {
2 // code goes here
3}
1// Worker
2function* getUsers() {
3 try {
4
5 } catch(e) {
6
7 }
8}
9
10// Watcher
11function* watchGetUsers() {
12 yield takeEvery(users.actions.getUsers, getUsers) // when this action is dispatched, run this function
13}
Blocking | Non-blocking |
---|---|
takeEvery |
call()
makes a function call. Could be another generator, or an API call, or a helper function imported from another file. We can yield a Promise directly,1const products = yield Api.fetch('/products')
but that makes unit testing difficult. So we use call()
instead
1// call(fn, ...args)
2const products = yield call(Api.fetch, '/products')