Reputation: 4392
I am from redux-thunk usage and aware of concept of middlewares where we used to get the api response and attach it to store with dispatch actions.In redux-thunk the code is in following format and with little knowledge of generator function I am aware that function stops at yield
and get triggers again only with .next
.Can someone explain below case
function* fetchUser(action) {
try {
const user = yield call(Api.fetchUser, action.payload.userId);
yield put({type: "USER_FETCH_SUCCEEDED", user: user});
} catch (e) {
yield put({type: "USER_FETCH_FAILED", message: e.message});
}
}
/*
Starts fetchUser on each dispatched `USER_FETCH_REQUESTED` action.
Allows concurrent fetches of user.
*/
function* mySaga() {
yield takeEvery("USER_FETCH_REQUESTED", fetchUser);
}
/*
Alternatively you may use takeLatest.
Does not allow concurrent fetches of user. If "USER_FETCH_REQUESTED" gets
dispatched while a fetch is already pending, that pending fetch is cancelled
and only the latest one will be run.
*/
function* mySaga() {
yield takeLatest("USER_FETCH_REQUESTED", fetchUser);
}
export default mySaga;
how does yield put
is called after yield call
without next
Upvotes: 1
Views: 655
Reputation: 4975
Redux sagas work like coroutines. That is, you are not responsible for iterating over the saga iterator. The saga library does this for you.
When you create your saga middleware and give it your root saga:
sagaMiddleware.run(rootSaga)
The saga library creates iterator of the rootSaga generator internally and calls next based on its internal logic. This is how it is able to read and handle the effects you are yielding in your sagas.
You are never calling next yourself when using redux-saga unless you are writing tests and simulating redux-saga behavior.
Upvotes: 2