Hello,
As we know Redux saga allows us to respond to actions outside Redux store. It's kind of middleware library to handle side effects with ease. This side effect could be anything like calling APIs, doing some IO operations or anything. While working with Saga sometime it happens that we also want to detect state changes and do some actions after it. In this blog I am going to explain how you can wait or detect Redux state changes with Saga.
Let's understand with an example. For example there is an API call to get access token and as soon as you have access toke available in state you want to call some other actions like background sync etc.
function* waitForLoginToken(selector) {
if (yield select(selector)) return;
while (true) {
yield take('*');
if (yield select(selector)) return;
}
}
export function* postSignInAction(payload) {
cost loginTokenSelector = state => state.auth.loginToken;
yield call(waitForLoginToken, loginTokenSelector);
yield put({ type: 'BACKGROUND_SYNC' });
}
function* mySaga(){
yield takeEvery('SIGN_IN', postSignInAction);
}
As you can see in above code, we take every sign in action and call postSignInAction which will wait for state change.
We defined state selector as state.auth.loginToken. Till the time loginToken is not set in state.auth it will wait as we are using while loop to wait for state change. Once we get it in state we call next action.
This way you can & detect state change with Redux Saga. Hope this helps you.