Search code examples
reactjstypescriptreduxredux-saga

React redux saga - using race has no effect at all


I have the following saga effect:

function* loginSaga() {
  const logoutTimeoutCreationDate: string | null = yield localStorage.getItem('logoutTimeoutCreationDate');

  let logoutTimeout: number;

  if (!logoutTimeoutCreationDate || +logoutTimeoutCreationDate + 5000 < new Date().getTime()) {
    yield localStorage.setItem('logoutTimeoutCreationDate', new Date().getTime().toString());

    logoutTimeout = yield 5000;
  } else {
    logoutTimeout = yield +logoutTimeoutCreationDate + 5000 - new Date().getTime();
  }
  
  yield race([
    function*() {
      yield delay(logoutTimeout);
      yield put(authActions.logout());
    },
    function*() {
      yield take(authActions.AUTH_LOGOUT);
    },
  ]);
}

All the code before yield race(..) works as expected, but the yield race(..) has no effect. Meaning like it does not even exist. I insert console.log()s line to check it (inside the function*() {...}) in both - but nothing got consoled.

What's wrong?


Solution

  • You should use other syntax without yield:

      const [delayAction]: [CallEffect, TakeEffect] = yield race<CallEffect | TakeEffect>([
        delay(logoutTimeout),
        take(authActions.AUTH_LOGOUT)
      ]);
    
      if(delayAction){
        yield put(authActions.logout());
      }