redux-saga/effects#race JavaScript Examples

The following examples show how to use redux-saga/effects#race. 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 5 votes vote down vote up
export function* raceWithResetForecast(effect) {
  return yield race({
    result: effect,
    reset: take(forecastUIActions.RESET_FORECAST),
  });
}
Example #2
Source File: user.js    From ant-simple-pro with MIT License 5 votes vote down vote up
effects = {
  *getMenTree() {
    try {
      const res = yield call(getAccessMenuList);
      yield put(loadingMenuTree(false));

      if (res.code === requestCode.successCode) {
        yield race([put(loadingMenuTree(true)), put(getMenuTree(res.data))])
      }

    } catch (error) {
      yield put(getMenuTree([]));
    }
  },

  *getMenuList({ payload }) {
    try {
      const res = yield call(getAccessMenu, payload);

      let { list = [], total = 0 } = res.data;

      if (res.code === requestCode.successCode && list.length) {
        list = list.map((item) => Object.assign({}, item, { createTime: tools.formatDate(item.createTime, 'YYYY-MM-DD hh:mm:ss') }));
      }

      yield put(getMenuList({ list, total }));

    } catch (error) {
      yield put(getMenuList({ list: [], total: 0 }));
    }
  },

  *getUserData({ payload }) {
    try {
      const res = yield call(userList, payload);

      res.code === requestCode.successCode && (yield put(getUserList(res.data)));
    } catch (error) {
      yield put(getUserList([]));
    }
  },

  *getUserInfoData() {
    try {
      const res = yield call(userInfo);

      yield put(loadingUserInfo(false));

      res.code === requestCode.successCode && (yield race([put(loadingUserInfo(true)), put(getUserInfo(res.data))]));
    } catch (error) {
      yield put(getUserInfo({}));
    }
  },
}
Example #3
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;
}