redux-saga/effects#cancel JavaScript Examples

The following examples show how to use redux-saga/effects#cancel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: forecast.js    From jc-calendar with MIT License 6 votes vote down vote up
export function* watchGetForecast() {
  let task;
  while (true) {
    const action = yield take(forecastUIActions.GET_FORECAST);
    if (task) {
      yield cancel(task);
    }
    task = yield fork(getForecastDebounced, action);
  }
}
Example #2
Source File: SagaManager.js    From movies with MIT License 6 votes vote down vote up
function createAbortableSaga(saga) {
  if (process.env.NODE_ENV === 'development') {
    return function* main() {
      const sagaTask = yield fork(saga);

      yield take(CANCEL_SAGAS_HMR);
      yield cancel(sagaTask);
    };
  }
  return saga;
}
Example #3
Source File: index.js    From stayaway-app with European Union Public License 1.2 5 votes vote down vote up
export function* startTracing() {
  if (Configuration.UI) {
    yield put(accountActions.setTracingEnabled(true));
    yield put(accountActions.startTracingResult(TRACING_RESULTS.SUCCESS));
    yield take(accountTypes.STOP_TRACING);
    yield put(accountActions.stopTracingResult(TRACING_RESULTS.SUCCESS));
    return;
  }

  const watcher = yield fork(watchTracingStatus);

  // Wait for listener to registered
  yield take(accountTypes.TRACING_STATUS_LISTENER_REGISTERED);
  try {
    const result = yield call(TracingManager.start);

    if (result === GAEN_RESULTS.EN_CANCELLED) {
      if (Platform.OS === 'android') {
        // Show alert
        Alert.alert(
          i18n.translate('common.dialogs.gaen.enable.title'),
          i18n.translate('common.dialogs.gaen.enable.description'),
          [
            {
              text: i18n.translate('common.actions.ok'),
              style: 'default',
            },
          ],
        );
      }

      yield put(accountActions.startTracingResult(TRACING_RESULTS.GAEN));
      yield cancel(watcher);
      return;
    }

    try {
      yield call(TracingManager.sync);

      // Get status
      const status = yield call(TracingManager.getStatus);
      yield put(accountActions.updateStatus(status));
    } catch (error) {
      // Sync error. Probably exposure check limit reached.
      // Clear errors
      yield put(accountActions.setErrors([]));
      console.log(error);
    }

    yield put(accountActions.startTracingResult(TRACING_RESULTS.SUCCESS));
  } catch (error) {
    console.log(error);
    yield put(accountActions.startTracingResult(TRACING_RESULTS.FAILED));
    yield cancel(watcher);
    return;
  }

  try {
    yield take(accountTypes.STOP_TRACING);
    yield cancel(watcher);
    yield call(TracingManager.stop);
    yield put(accountActions.stopTracingResult(TRACING_RESULTS.SUCCESS));
  } catch (error) {
    console.log(error);
    yield put(accountActions.stopTracingResult('ERROR'));
  }
}
Example #4
Source File: saga.js    From react-redux-saga-sample with MIT License 4 votes vote down vote up
createAuthSaga = (options: {
  loginActions?: Object,
  reducerKey: string,
  OAUTH_URL: string,
  OAUTH_CLIENT_ID: string,
  OAUTH_CLIENT_SECRET: string,
}) => {
  const {
    loginActions,
    OAUTH_URL,
    OAUTH_CLIENT_ID,
    OAUTH_CLIENT_SECRET,
    reducerKey,
  } = options;

  const getAuth = state => state[reducerKey];

  function* RefreshToken(refresh_token) {
    try {
      const params = {
        refresh_token,
        client_id: OAUTH_CLIENT_ID,
        client_secret: OAUTH_CLIENT_SECRET,
        grant_type: "refresh_token",
      };
      const { data: token } = yield call(axios.post, OAUTH_URL, params);
      yield put(authRefreshSuccess(token));
      return true;
    } catch (error) {
      if (error.response) {
        if (error.response.status === 401) {
          yield put(authInvalidError(error.response));
        } else {
          yield put(authRefreshError(error.response));
        }
      } else {
        yield put(authRefreshError(error));
      }
      return false;
    }
  }

  function* RefreshLoop() {
    const maxRetries = 5;
    let retries = 0;

    while (true) {
      const { expires_in, created_at, refresh_token } = yield select(getAuth);

      // if the token has expired, refresh it
      if (
        expires_in !== null &&
        created_at !== null &&
        tokenHasExpired({ expires_in, created_at })
      ) {
        const refreshed = yield call(RefreshToken, refresh_token);

        // if the refresh succeeded set the retires to 0
        // if the refresh failed, log a failure
        if (refreshed) {
          // if the token has been refreshed, and their had been retries
          // let the user know everything is okay
          if (retries > 0) {
            // @TODO add hook
          }
          retries = 0;
        } else {
          retries = retries + 1;
        }

        if (retries > 0 && retries < maxRetries) {
          // @TODO add hook
        }

        if (retries === maxRetries) {
          // @TODO add hook
        }
      }

      // check again in 5 seconds
      // this will also replay failed refresh attempts
      yield delay(5000);
    }
  }

  function* Authorize(action) {
    try {
      const { onSuccess, payload } = action;

      const params = {
        ...payload,
        client_id: OAUTH_CLIENT_ID,
        client_secret: OAUTH_CLIENT_SECRET,
      };

      const { data: token } = yield call(axios.post, OAUTH_URL, params);
      yield put(authLogin(token));

      if (onSuccess) {
        onSuccess();
      }
    } catch (error) {
      const { onError } = action;

      if (onError) {
        onError(error.response ? error.response.data : error);
      }

      if (error.response) {
        yield put(authLoginError(error.response.data));
      } else {
        yield put(authLoginError(error));
      }
    }
  }

  function* Authentication(): Generator<*, *, *> {
    while (true) {
      const { loggedIn } = yield select(getAuth);
      var authorizeTask = null;

      // if the users is logged in, we can skip over this bit
      if (!loggedIn) {
        // wait for a user to request to login
        // or any custom login actions
        const actions = yield race({
          login: take(AUTH_LOGIN_REQUEST),
          ...loginActions,
        });

        if (actions.login) {
          // in the background, run a task to log them in
          authorizeTask = yield fork(Authorize, actions.login);
        }
      } else {
        // dispatch an action so we know the user is back into an
        // authenticated state
        yield put(authRestore());
      }

      // wait for...
      // the user to logout (AUTH_LOGOUT_REQUEST)
      // OR an error to occur during login (AUTH_LOGIN_ERROR)
      // OR the user to become unauthorized (AUTH_INVALID_ERROR)
      // but while they are logged in, begin the refresh token loop
      const actions = yield race({
        logout: take(AUTH_LOGOUT_REQUEST),
        loginError: take(AUTH_LOGIN_ERROR),
        unauthorized: take(AUTH_INVALID_ERROR),
        refresh: call(RefreshLoop),
      });

      // cancel the authorizeTask task if it's running and exists
      if (authorizeTask !== null) {
        yield cancel(authorizeTask);
      }

      // finally log the user out
      yield put(authLogout());
    }
  }

  return Authentication;
}