redux-saga/effects#delay JavaScript Examples

The following examples show how to use redux-saga/effects#delay. 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: user.js    From full-stack-fastapi-react-postgres-boilerplate with MIT License 6 votes vote down vote up
/**
 * Login
 */
export function* login() {
  try {
    yield delay(400);

    yield put({
      type: ActionTypes.USER_LOGIN_SUCCESS,
    });
  } catch (err) {
    /* istanbul ignore next */
    yield put({
      type: ActionTypes.USER_LOGIN_FAILURE,
      payload: err,
    });
  }
}
Example #2
Source File: user.js    From full-stack-fastapi-react-postgres-boilerplate with MIT License 6 votes vote down vote up
/**
 * Logout
 */
export function* logout() {
  try {
    yield delay(200);

    yield put({
      type: ActionTypes.USER_LOGOUT_SUCCESS,
    });
  } catch (err) {
    /* istanbul ignore next */
    yield put({
      type: ActionTypes.USER_LOGOUT_FAILURE,
      payload: err,
    });
  }
}
Example #3
Source File: user.sagas.js    From horondi_client_fe with MIT License 6 votes vote down vote up
export function* handleUserRecovery({ payload }) {
  try {
    yield put(resetState());
    yield put(setRecoveryLoading(true));
    yield call(recoverUser, payload);
    yield put(setRecoveryLoading(false));
    yield put(userHasRecovered(true));
    if (payload.redirect) {
      yield delay(REDIRECT_TIMEOUT);
      yield put(push(pathToLogin));
    }
  } catch (e) {
    yield call(handleUserError, e);
  }
}
Example #4
Source File: user.sagas.js    From horondi_client_fe with MIT License 6 votes vote down vote up
export function* handlePasswordReset({ payload }) {
  try {
    yield put(resetState());
    yield put(setUserLoading(true));
    yield call(resetPassword, payload);
    yield put(setUserLoading(false));
    yield put(setPasswordIsReset(true));
    yield delay(REDIRECT_TIMEOUT);
    yield put(push(pathToLogin));
  } catch (e) {
    yield call(handleUserError, e);
  }
}
Example #5
Source File: actions.js    From what-front with MIT License 6 votes vote down vote up
function* addAlertAsync({ payload }) {
  const { message, variant, delayTime } = payload;
  const id = Date.now();

  yield put({
    type: actionTypes.SHOW_ALERT,
    payload: {
      id,
      message,
      variant,
    },
  });

  yield delay(delayTime);

  yield put(removeAlert(id));
}
Example #6
Source File: saga.js    From bank-client with MIT License 6 votes vote down vote up
export function* checkEmail({ value, reject, resolve }) {
  const requestURL = api.users('checkEmail')(value);

  if (!value) {
    yield call(resolve);
  }

  if (emailValidation(value)) {
    try {
      yield delay(400);
      const { exist } = yield call(request, requestURL);
      yield put(checkEmailSuccessAction(exist));

      if (exist) {
        yield call(reject);
      } else {
        yield call(resolve);
      }
    } catch (error) {
      const message = <FormattedMessage {...messages.serverError} />;
      yield put(checkEmailErrorAction(message));
    }
  } else {
    yield put(checkEmailInvalidAction());
    yield call(resolve);
  }
}
Example #7
Source File: saga.js    From bank-client with MIT License 6 votes vote down vote up
export function* searchRecipient({ value }) {
  const { accessToken } = yield select(makeSelectToken());
  const requestURL = api.bills('search')(value);
  const requestParameters = {
    method: 'GET',
    headers: { Authorization: `Bearer ${accessToken}` },
  };

  if (!numberValidation(value)) {
    return;
  }

  if (value.length > 1) {
    yield delay(300);
  }

  try {
    const { data } = yield call(request, requestURL, requestParameters);
    yield put(searchRecipientSuccessAction(data));
  } catch (error) {
    yield put(searchRecipientErrorAction(error));

    switch (error.statusCode) {
      case 401:
        yield put(push(routes.login.path));
        break;
      default:
        yield put(push(routes.login.path));
        break;
    }
  }
}
Example #8
Source File: saga.js    From rysolv with GNU Affero General Public License v3.0 6 votes vote down vote up
export function* sendFormSaga({ payload }) {
  const { body, email, name } = payload;
  const query = `
    mutation {
      sendContact(
        contactInput: {
          body: ${JSON.stringify(body)}
          contactName: "${name}"
          email: ${JSON.stringify(email)}
          source: "contact"
        }
      ) {
        __typename
        ... on Success {
          message
        }
        ... on Error {
          message
        }
      }
    }
  `;
  try {
    const graphql = JSON.stringify({ query });
    const {
      data: {
        sendContact: { __typename, message },
      },
    } = yield call(post, '/graphql', graphql);
    if (__typename === 'Error') throw message;
    yield delay(500);
    yield put(sendFormSuccess());
  } catch (error) {
    yield delay(500);
    yield put(sendFormFailure());
  }
}
Example #9
Source File: forecast.js    From jc-calendar with MIT License 5 votes vote down vote up
export function* getForecastDebounced(action) {
  const { reset } = yield raceWithResetForecast(delay(1000));
  if (!reset) {
    yield getForecast(action);
  }
}
Example #10
Source File: saga.js    From real-frontend with GNU General Public License v3.0 5 votes vote down vote up
/**
 *
 */
function* postsCreateRequest(req) {
  try {
    const data = yield handlePostsCreateRequest(req.payload)

    const channel = yield call(initPostsCreateUploadChannel, {
      imageUrl: data.imageUrl,
      image: data.image,
    })

    yield takeEvery(channel, function *(upload) {
      const meta = {
        attempt: upload.attempt || req.payload.attempt,
        progress: parseInt(upload.progress, 10),
      }

      if (upload.status === 'progress') {
        yield put(actions.postsCreateProgress({ data: {}, payload: req.payload, meta }))
      }

      if (upload.status === 'success') {
        yield delay(3000)
        yield put(actions.postsCreateSuccess({ data: {}, payload: req.payload, meta }))
        yield delay(5000)
        yield put(actions.postsCreateIdle({ data: {}, payload: req.payload, meta }))
      }

      if (upload.status === 'failure') {
        yield put(actions.postsCreateFailure({ data: {}, payload: req.payload, meta }))
      }
    })
  } catch (error) {
    yield put(actions.postsCreateFailure({
      message: error.message,
      payload: req.payload,
      meta: { attempt: 0, progress: 0 },
    }))
  }
}
Example #11
Source File: saga.js    From rysolv with GNU Affero General Public License v3.0 5 votes vote down vote up
export function* editPositionSaga({ payload }) {
  const { companyId, positionId, responseArray } = payload;
  const formattedResponse = responseArray.map(
    ({ questionId, questionKey, responseId, value }) => {
      const generateFormattedValue = () => {
        switch (questionKey) {
          case 'description': {
            return `${JSON.stringify(value)}`;
          }
          case 'location': {
            return `{
              country: "${value.country}",
              countryCode: "${value.countryCode}",
              formattedAddress: "${value.formattedAddress}",
              utcOffset: ${value.utcOffset}
            }`;
          }
          case 'skills': {
            return `{
              beginner: ${value.beginner},
              expert: ${value.expert},
              intermediate: ${value.intermediate},
              skill: "${value.skill}"
            }`;
          }
          default: {
            return `"${value}"`;
          }
        }
      };
      const formattedValue = generateFormattedValue();
      return `{
        questionId: "${questionId}",
        questionKey: "${questionKey}",
        responseId: "${responseId}",
        value: ${formattedValue},
      }`;
    },
  );
  const query = `
    mutation {
      transformPositionResponse(
        positionId: "${positionId}",
        responseArray: [${formattedResponse}]
      ) {
        __typename
        ... on Success {
          message
        }
        ... on Error {
          message
        }
      }
    }
  `;
  try {
    const graphql = JSON.stringify({ query });
    const {
      data: {
        transformPositionResponse: { __typename, message },
      },
    } = yield call(post, '/graphql', graphql);
    if (__typename === 'Error') throw message;
    yield put(editPositionSuccess());
    yield put(fetchCompanyPositions({ companyId }));
    yield put(matchCandidates({ positionId }));
    yield delay(500);
    yield put(push('/company/dashboard'));
  } catch (error) {
    yield put(editPositionFailure({ error: { message: error } }));
  }
}
Example #12
Source File: index.js    From stayaway-app with European Union Public License 1.2 5 votes vote down vote up
export function* setupNewAccount() {
  yield put(accountActions.setupNewAccountPending());

  // Set default state
  yield put(accountActions.updateStatus({
    lastSyncDate: 0,
    infectionStatus: 0,
    exposureDays: [],
    errors: [],
  }));

  // Check if permissions are all granted
  yield put(permissionsActions.checkAllPermissions());
  const { payload: allPermissionsGranted } = yield take(permissionsTypes.CHECK_ALL_PERMISSIONS_RESULT);

  if (! allPermissionsGranted) {
    // Request permissions
    yield put(permissionsActions.requestAllPermissions());
    yield take(permissionsTypes.REQUEST_ALL_PERMISSIONS_RESULT);
  }

  // Start tracing manager
  if (Configuration.UI) {
    yield put(accountActions.updateStatus({
      lastSyncDate: Moment().toJSON(),
      infectionStatus: 0,
      exposureDays: [],
      errors: [],
    }));
  }

  yield put(accountActions.startTracing());
  const { payload } = yield take(accountTypes.START_TRACING_RESULT);

  if (payload === TRACING_RESULTS.SUCCESS) {
    // Set tracing activated
    yield put(accountActions.setTracingEnabled(true));
  } else if (payload === TRACING_RESULTS.GAEN) {
    yield put(accountActions.setTracingEnabled(false));

    // Add tracing error
    yield put(accountActions.setErrors([ERRORS[Platform.OS].GAEN_UNEXPECTEDLY_DISABLED]));
  } else {
    yield put(accountActions.setTracingEnabled(false));
  }

  // Update new account redux
  yield put(accountActions.setSignUpDate(Moment().toJSON()));

  // Delay 1 second
  yield delay(1000);

  // Navigate to home
  yield put(onboardingActions.setOnboarding(false));
  yield put(accountActions.setupNewAccountDone());
  NavigationService.navigate(AppRoutes.APP);
}
Example #13
Source File: index.js    From stayaway-app with European Union Public License 1.2 5 votes vote down vote up
function* watchAppStateChange() {
  const channel = eventChannel((emitter) => {
    AppState.addEventListener('change', emitter);
    return () => AppState.removeEventListener('change', emitter);
  });

  try {
    let previousState = 'unknown';

    while (true) {
      const nextState = yield take(channel);
      const onboarding = yield select(isOnboarding);

      if (! onboarding && previousState !== nextState) {
        if (nextState === 'active') {
          const isProtectorOpen = yield select(isProtectorModalOpen);
          if (isProtectorOpen) {
            yield delay(200);
            yield put(modalsActions.closeProtectorModal());
            yield take(modalsTypes.PROTECTOR_MODAL_CLOSED);
          }

          try {
            if (! Configuration.UI) {
              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.
            console.log(error);
          }
        } else if (nextState === 'inactive') {
          const isProtectorOpen = yield select(isProtectorModalOpen);
          if (! isProtectorOpen) {
            yield put(modalsActions.openProtectorModal());
            yield take(modalsTypes.PROTECTOR_MODAL_OPEN);
          }
        }
      }

      previousState = nextState;
    }
  } finally {
    channel.close();
  }
}
Example #14
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;
}
Example #15
Source File: index.js    From stayaway-app with European Union Public License 1.2 4 votes vote down vote up
export function* submitDiagnosis({ payload: code }) {
  // Open loading modal
  yield put(accountActions.submitDiagnosisPending());
  yield put(modalsActions.openLoadingModal());
  yield take(modalsTypes.LOADING_MODAL_OPEN);

  try {
    if (Configuration.UI) {
      // Delay 1.5 seconds
      yield delay(1500);

      // Mark as infected
      yield put(accountActions.setInfectionStatus(INFECTION_STATUS.INFECTED));

      // Stop tracing
      yield put(accountActions.setTracingEnabled(false));

      yield put(accountActions.submitDiagnosisDone());
      yield put(modalsActions.closeLoadingModal());
      yield take(modalsTypes.LOADING_MODAL_CLOSED);

      return;
    }

    // Submit exposed code
    const result = yield call(TracingManager.exposed, code);

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

      yield put(accountActions.submitDiagnosisDone());
      yield put(modalsActions.closeLoadingModal());
      yield take(modalsTypes.LOADING_MODAL_CLOSED);
      return;
    }

    // Update status
    yield put(accountActions.setInfectionStatus(INFECTION_STATUS.INFECTED));
    yield take(accountTypes.UPDATE_STATUS_RESULT);

    // Stop tracing
    yield call(TracingManager.removeUpdateEventListener);
    yield put(accountActions.setTracingEnabled(false));

    yield put(accountActions.submitDiagnosisDone());
    yield put(modalsActions.closeLoadingModal());
    yield take(modalsTypes.LOADING_MODAL_CLOSED);
  } catch (error) {
    console.log(error);

    yield put(accountActions.submitDiagnosisDone());
    yield put(modalsActions.closeLoadingModal());
    yield take(modalsTypes.LOADING_MODAL_CLOSED);

    if (error.message === ERRORS[Platform.OS].UNKNOWN_HOST_EXCEPTION.toString()) {
      yield put(accountActions.submitDiagnosisError(i18n.translate('common.errors.network')));
      yield put(modalsActions.openNetworkModal());
      yield take(modalsTypes.NETWORK_MODAL_OPEN);
    } else if (error.message === ERRORS[Platform.OS].INVALID_CODE_EXCEPTION.toString()) {
      yield put(accountActions.submitDiagnosisError(i18n.translate('common.errors.submit.code')));
      yield put(modalsActions.openInvalidCodeModal());
      yield take(modalsTypes.INVALID_CODE_MODAL_OPEN);
    } else {
      yield put(accountActions.submitDiagnosisError(i18n.translate('common.errors.general')));
      yield put(modalsActions.openServerErrorModal());
      yield take(modalsTypes.SERVER_ERROR_MODAL_OPEN);
    }
  }
}