redux-saga/effects#call TypeScript Examples

The following examples show how to use redux-saga/effects#call. 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: utils.ts    From marina with MIT License 7 votes vote down vote up
// redux-saga does not handle async generator
// this is useful to pass through this limitation
export function* processAsyncGenerator<NextType>(
  asyncGenerator: AsyncGenerator<NextType>,
  onNext: (n: NextType) => SagaGenerator,
  onDone?: () => SagaGenerator
): SagaGenerator<void, IteratorYieldResult<NextType>> {
  const next = () => asyncGenerator.next();
  let n = yield call(next);
  while (!n.done) {
    yield* onNext(n.value);
    n = yield call(next);
  }

  if (onDone && n.done) {
    yield* onDone();
  }
}
Example #2
Source File: sagas.ts    From generator-earth with MIT License 6 votes vote down vote up
function* submitFormAsync(action: Action4All) {
    
    // 初始化antd-table-pagination
    let _formData = Object.assign(
        {[PAGE_SIZE]: 10, [CURRENT_PAGE]: 1},
        action.payload,
    )
    
    // 请求server数据
    let result = yield call(request.post, '/asset/getAsset', _formData)
    
    if (!result) { return; }
    
    
    // 解构server结果
    let resultBody = result[RESPONSE_DESTRUST_KEY]
    
    if (!resultBody) { return; }
    
    // 更新formData
    yield put({ type: LIST__UPDATE_FORM_DATA, payload: {
        ..._formData,
        [TOTAL]: resultBody[TOTAL],
    } })
    
    // 更新tableData
    yield put({ type: LIST__UPDATE_TABLE_DATA, payload: {
        dataSource: resultBody[RESPONSE_LIST_DESTRUST_KEY],
    } })
    
}
Example #3
Source File: index.ts    From FLECT_Amazon_Chime_Meeting with Apache License 2.0 6 votes vote down vote up
function* handleCreateUser() {
    while (true) {
        const action = yield take('CREATE_USER');
        console.log(action)
        const userName     = action.payload[0]
        const code         = action.payload[1]
        const userNameEnc  = encodeURIComponent(userName)

        const url = `${API_BASE_URL}users?userName=${userNameEnc}`
        console.log(url)
        try{
            let data = yield call((url:string) =>{
                return fetch(url, {
                    method: 'POST',
                })
                .then(res => res.json())
                .catch(error => {throw error})
            }, url);
            console.log(data)
            yield put(Actions.userCreated(userName, data.userId, code));
        }catch(e){
            console.log('failed:'+e)
        }
    }
}
Example #4
Source File: RootSaga.ts    From rewind with MIT License 6 votes vote down vote up
function* busyPollBackendState(): SagaIterator {
  let state: BackendState = "NOT_STARTED"; // Maybe select from store?
  while (state === "NOT_STARTED" || state === "LOADING") {
    const newState: BackendState = yield call(fetchStatus);
    if (newState !== state) {
      yield put(stateChanged(newState));
      state = newState;
    }
    yield delay(BACKEND_STATE_BUSY_POLL_DURATION_IN_MS);
  }
}
Example #5
Source File: saga.ts    From celo-web-wallet with MIT License 6 votes vote down vote up
/**
 * A convenience utility to create a saga and trigger action
 * Use to create simple sagas, for more complex ones use createMonitoredSaga.
 * Note: the wrapped saga this returns must be added to rootSaga.ts
 */
export function createSaga<SagaParams = void>(saga: (...args: any[]) => any, name: string) {
  const triggerAction = createAction<SagaParams>(`${name}/trigger`)

  const wrappedSaga = function* () {
    while (true) {
      try {
        const trigger: Effect = yield take(triggerAction.type)
        logger.debug(`${name} triggered`)
        yield call(saga, trigger.payload)
      } catch (error) {
        logger.error(`${name} error`, error)
      }
    }
  }

  return {
    wrappedSaga,
    trigger: triggerAction,
  }
}
Example #6
Source File: sagas.ts    From firebase-tools-ui with Apache License 2.0 6 votes vote down vote up
// TODO(kirjs): Figure out what's the deal with all those new anys.
export function* fetchAuthUsers(): any {
  const authApi = yield call(configureAuthSaga);
  try {
    const users = yield call([authApi, 'fetchUsers']);
    yield put(authFetchUsersSuccess(users));
  } catch (e) {
    yield put(authFetchUsersError({ message: 'Error when fetching users' }));
  }
}
Example #7
Source File: Checkout.saga.ts    From react-native-woocommerce with MIT License 6 votes vote down vote up
export function* sendOrder({ payload: order }: { payload: object }) {
  try {
    const { id, order_key } = yield call(sendOrderAPI, order);

    if (!!id && !!order_key) {
      const paymentUrl =
          `${config.WC_BASE_URL}/checkout/order-pay/${id}?pay_for_order=true&key=${order_key}`;

      yield put(actions.checkoutResponse());
      yield Linking.openURL(paymentUrl);
    }
  } catch (error) {
    yield call(handleError, error);
  } finally {
    yield put(appActions.setRenderable());
  }
}
Example #8
Source File: newsFeedSaga.ts    From foodie with MIT License 6 votes vote down vote up
function* newsFeedSaga({ type, payload }: INewsFeedSaga) {
    switch (type) {
        case GET_FEED_START:
            try {
                yield put(isGettingFeed(true));
                yield put(setNewsFeedErrorMessage(null));

                const posts: IPost[] = yield call(getNewsFeed, payload);

                yield put(isGettingFeed(false));
                yield put(getNewsFeedSuccess(posts));
            } catch (e) {
                console.log(e);
                yield put(isGettingFeed(false));
                yield put(setNewsFeedErrorMessage(e))
            }

            break;
        case CREATE_POST_START:
            try {
                yield put(isCreatingPost(true));

                const post: IPost = yield call(createPost, payload);

                yield put(createPostSuccess(post));
                yield put(isCreatingPost(false));
                toast.dismiss();
                toast.dark('Post succesfully created.');
            } catch (e) {
                yield put(isCreatingPost(false));
                console.log(e);
            }
            break;
        default:
            throw new Error('Unexpected action type.')
    }
}
Example #9
Source File: saga.ts    From mamori-i-japan-admin-panel with BSD 2-Clause "Simplified" License 6 votes vote down vote up
function* getAdminUsersSaga() {
  yield takeEvery(actionTypes.GET_ADMIN_USERS, function* _() {
    yield put({
      type: loadingActionTypes.START_LOADING,
    });

    yield call(getAccessTokenSaga);

    try {
      const res = yield call(getAdminUsers);

      const data = res.data.map((item: any) => {
        return {
          ...item,
          createdAt: item.createdAt ? item.createdAt._seconds : null
        }
      })

      yield put({
        type: actionTypes.GET_ADMIN_USERS_SUCCESS,
        payload: {
          listData: data,
        },
      });
    } catch (error) {
      yield put({
        type: feedbackActionTypes.SHOW_ERROR_MESSAGE,
        payload: { errorCode: error.status, errorMessage: error.error },
      });
    }

    yield put({
      type: loadingActionTypes.END_LOADING,
    });
  });
}
Example #10
Source File: saga.test.ts    From react-js-tutorial with MIT License 6 votes vote down vote up
it("works with dynamic static providers", () => {
  return expectSaga(someSaga)
    .provide([
      [matchers.call.fn(add2), dynamic(provideDoubleIf6)],
      [matchers.call.fn(add2), dynamic(provideTripleIfGt4)],
    ])
    .put({ type: "DONE", payload: 42 })
    .run();
});
Example #11
Source File: api.ts    From orangehrm-os-mobile with GNU General Public License v3.0 6 votes vote down vote up
export function* apiGetCall(endpoint: string, requiredRawResponse?: boolean) {
  const authParams: AuthParams = yield selectAuthParams();

  if (authParams.accessToken !== null && authParams.instanceUrl !== null) {
    const headers = new Headers();
    headers.append('Authorization', `Bearer ${authParams.accessToken}`);
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');

    const requestOptions = {
      method: 'GET',
      headers: headers,
    };
    const url = authParams.instanceUrl + endpoint;

    const response: Response = yield call(fetch, url, requestOptions);

    if (requiredRawResponse === true) {
      return response;
    }
    const data = yield call([response, response.json]);
    data.getResponse = () => {
      return response;
    };
    return data;
  }
  throw new Error("Couldn't call with empty instanceUrl or accessToken.");
}
Example #12
Source File: user-saga.ts    From Riakuto-StartingReact-ja3.1 with Apache License 2.0 6 votes vote down vote up
function* runGetMembers(
  action: ReturnType<typeof userSlice.actions.getMembersStarted>,
) {
  const { orgCode } = action.payload;

  try {
    const users = (yield call(getMembers, orgCode)) as User[];

    yield put(
      getMembersSucceeded({
        params: { orgCode },
        result: { users },
      }),
    );
  } catch (error) {
    if (error instanceof Error) {
      yield put(getMembersFailed({ params: { orgCode }, error }));
    }
  }
}
Example #13
Source File: index.ts    From slice-machine with Apache License 2.0 6 votes vote down vote up
export function* createCustomTypeSaga({
  payload,
}: ReturnType<typeof createCustomTypeCreator.request>) {
  try {
    const newCustomType = createCustomType(
      payload.id,
      payload.label,
      payload.repeatable
    );
    yield call(saveCustomType, newCustomType, {});
    yield put(createCustomTypeCreator.success({ newCustomType }));
    yield put(
      modalCloseCreator({ modalKey: ModalKeysEnum.CREATE_CUSTOM_TYPE })
    );
    yield put(push(`/cts/${payload.id}`));
    yield put(
      openToasterCreator({
        message: "Custom type saved",
        type: ToasterType.SUCCESS,
      })
    );
  } catch (e) {
    yield put(
      openToasterCreator({
        message: "Internal Error: Custom type not saved",
        type: ToasterType.ERROR,
      })
    );
  }
}
Example #14
Source File: saga.ts    From react-boilerplate-cra-template with MIT License 6 votes vote down vote up
/**
 * Github repos request/response handler
 */
export function* getRepos() {
  yield delay(500);
  // Select username from store
  const username: string = yield select(selectUsername);
  if (username.length === 0) {
    yield put(actions.repoError(RepoErrorType.USERNAME_EMPTY));
    return;
  }
  const requestURL = `https://api.github.com/users/${username}/repos?type=all&sort=updated`;

  try {
    // Call our request helper (see 'utils/request')
    const repos: Repo[] = yield call(request, requestURL);
    if (repos?.length > 0) {
      yield put(actions.reposLoaded(repos));
    } else {
      yield put(actions.repoError(RepoErrorType.USER_HAS_NO_REPO));
    }
  } catch (err: any) {
    if (err.response?.status === 404) {
      yield put(actions.repoError(RepoErrorType.USER_NOT_FOUND));
    } else if (err.message === 'Failed to fetch') {
      yield put(actions.repoError(RepoErrorType.GITHUB_RATE_LIMIT));
    } else {
      yield put(actions.repoError(RepoErrorType.RESPONSE_ERROR));
    }
  }
}
Example #15
Source File: sagas.ts    From rhub-app with MIT License 6 votes vote down vote up
function* load(action: AnyAction): any {
  const { clusterId, parameters, nameCheck } = action.payload;
  const queryString = `lab/cluster${
    clusterId === 'all' ? '' : `/${clusterId}`
  }`;
  try {
    const response = yield call(api.get, queryString, { params: parameters });
    if (clusterId !== 'all') {
      yield put(actions.loadSuccess(clusterId, response.data));
      yield put(actions.loadEventRequest(clusterId));
      yield put(actions.loadHostRequest(clusterId));
    } else
      yield put(actions.loadSuccess(clusterId, response.data.data, nameCheck));
  } catch (err) {
    yield put(actions.loadFailure());
  }
}
Example #16
Source File: main.ts    From marina with MIT License 6 votes vote down vote up
function* fetchTaxiAssetsForNetwork(network: NetworkString): SagaGenerator<void, string[]> {
  try {
    const assets = yield call(fetchAssetsFromTaxi, taxiURL[network]);
    const currentTaxiAssets = yield* newSagaSelector(selectTaxiAssetsForNetwork(network))();
    const sortAndJoin = (a: string[]) => a.sort().join('');
    if (sortAndJoin(assets) !== sortAndJoin(currentTaxiAssets)) {
      yield put(setTaxiAssets(network, assets));
    }
  } catch (err: unknown) {
    console.warn(`fetch taxi assets error: ${(err as Error).message || 'unknown'}`);
    // ignore errors
  }
}
Example #17
Source File: index.ts    From FLECT_Amazon_Chime_Meeting with Apache License 2.0 5 votes vote down vote up
function* handleLoginUser() {
    while (true) {
        const action = yield take('LOGIN');
        console.log(action)
        const userName     = action.payload[0]
        const code         = action.payload[1]
        const userNameEnc  = encodeURIComponent(userName)
        const codeEnc      = encodeURIComponent(code)

        // get userId
        const url = `${API_BASE_URL}users?userName=${userNameEnc}`
        console.log(url)
        let userData
        try{
            userData = yield call((url:string) =>{
                return fetch(url, {
                    method: 'GET',
                })
                .then(res => res.json())
                .catch(error => {throw error})
            }, url);
            console.log(userData)
        }catch(e){
            console.log('failed:'+e)
        }

        // login
        const url2 = `${API_BASE_URL}users/${userData.userId}/execLogin?code=${codeEnc}`
        console.log(url2)

        try{
            let userData = yield call((url2:string) =>{
                return fetch(url2, {
                    method: 'POST',
                })
                .then(res => res.json())
                .catch(error => {throw error})
            }, url2);
            console.log(userData)
            yield put(Actions.userLogined(userName, userData.userId, code));
        }catch(e){
            console.log('failed:'+e)
        }
    }
}
Example #18
Source File: RootSaga.ts    From rewind with MIT License 5 votes vote down vote up
function* watchForBackendReady(theater: RewindTheater): SagaIterator {
  const { common, analyzer } = theater;
  yield call(waitForBackendState, "READY");
  yield call(common.initialize.bind(common));
  yield call(analyzer.startWatching.bind(analyzer));
  yield put(push("/analyzer")); // Theater
}
Example #19
Source File: rootSaga.ts    From celo-web-wallet with MIT License 5 votes vote down vote up
// Things that should happen before other sagas start go here
function* init() {
  yield call(initProvider)
}
Example #20
Source File: sagas.ts    From firebase-tools-ui with Apache License 2.0 5 votes vote down vote up
export function* deleteUser({ payload }: ReturnType<typeof deleteUserRequest>) {
  const authApi: AuthApi = yield call(configureAuthSaga);

  yield call([authApi, 'deleteUser'] as any, {
    localId: payload.localId,
  });
  yield put(deleteUserSuccess({ localId: payload.localId }));
}
Example #21
Source File: Checkout.saga.ts    From react-native-woocommerce with MIT License 5 votes vote down vote up
export function* sendOrderAPI(order: object) {
  const { data } = yield call(WooCommerce.post, '/orders', order);

  return data;
}
Example #22
Source File: authSaga.ts    From foodie with MIT License 5 votes vote down vote up
function* authSaga({ type, payload }: IAuthSaga) {
    switch (type) {
        case LOGIN_START:
            try {
                yield put(isAuthenticating(true));
                const { auth } = yield call(login, payload.email, payload.password);
                socket.emit('userConnect', auth.id);
                yield put(clearNewsFeed());
                yield put(loginSuccess(auth));
                yield put(isAuthenticating(false));
            } catch (e) {
                console.log(e);

                yield handleError(e);
            }
            break;
        case CHECK_SESSION:
            try {
                yield put(isAuthenticating(true));
                const { auth } = yield call(checkAuthSession);

                console.log('SUCCESS ', auth);
                yield put(loginSuccess(auth));
                yield put(isAuthenticating(false));
            } catch (e) {
                yield handleError(e);
            }
            break;
        case LOGOUT_START:
            try {
                const { auth } = yield select();
                yield put(isAuthenticating(true));
                yield call(logout);

                payload.callback && payload.callback();

                yield put(logoutSuccess());
                yield put(isAuthenticating(false));
                yield put(clearNewsFeed());
                yield put(clearChat());
                history.push(LOGIN);
                socket.emit('userDisconnect', auth.id);
            } catch (e) {
                yield handleError(e);
            }
            break;
        case REGISTER_START:
            try {
                yield put(isAuthenticating(true));

                const user: IUser = yield call(register, payload);

                socket.emit('userConnect', user.id);
                yield put(registerSuccess(user));
                yield put(isAuthenticating(false));
            }
            catch (e) {
                console.log('ERR', e);
                yield handleError(e);
            }
            break;
        default:
            return;
    }
}
Example #23
Source File: saga.ts    From mamori-i-japan-admin-panel with BSD 2-Clause "Simplified" License 5 votes vote down vote up
function* createAdminUserSaga() {
  yield takeEvery(actionTypes.CREATE_ADMIN_USER, function* _({ payload }: any) {
    const { email, role: adminRole, organization, prefecture } = payload.data;

    yield put({
      type: loadingActionTypes.START_LOADING,
    });

    yield call(getAccessTokenSaga);

    const requestBody: any = {
      email,
      adminRole: adminRoleList[adminRole],
    };

    if (organization) {
      requestBody.organizationId = organization;
    }

    if (prefecture) {
      requestBody.prefectureId = Number.parseInt(prefectureList[prefecture].id);
    }

    try {
      yield call(postAdminUser, requestBody);

      yield call(sendEmailSaga, email);

      yield put({
        type: feedbackActionTypes.SHOW_SUCCESS_MESSAGE,
        payload: { successMessage: 'createAdminUserSuccess' },
      });

      payload.callback();
    } catch (error) {
      const errorMessage = error.status === 409 ? 'adminUserIsExistError' : error.error;

      yield put({
        type: feedbackActionTypes.SHOW_ERROR_MESSAGE,
        payload: {
          errorCode: error.status,
          errorMessage: errorMessage
        }
      });
    }

    yield put({
      type: loadingActionTypes.END_LOADING,
    });
  });
}
Example #24
Source File: saga.test.ts    From react-js-tutorial with MIT License 5 votes vote down vote up
function* someSaga() {
  const x = yield call(add2, 4);
  const y = yield call(add2, 6);
  const z = yield call(add2, 8);

  yield put({ type: "DONE", payload: x + y + z });
}
Example #25
Source File: sagas.ts    From orangehrm-os-mobile with GNU General Public License v3.0 5 votes vote down vote up
function* fetchEnabledModules(action?: FetchEnabledModulesAction) {
  try {
    if (action) {
      yield openLoader();
    }
    const instanceUrl: string = yield selectInstanceUrl();
    const response: Response = yield call(getEnabledModules, instanceUrl);

    if (response.ok) {
      const responseData = yield call([response, response.json]);

      if (responseData.data) {
        yield put(fetchEnabledModulesFinished(responseData.data));
        if (!responseData.data.modules.mobile) {
          // Logout in case loggedin user
          yield* logout();
          throw new InstanceCheckError(
            'The Mobile App Is Not Enabled, Please Contact Your System Administrator.',
          );
        }
      } else {
        throw new InstanceCheckError('Failed to Load Enabled Modules.');
      }
    } else {
      throw new InstanceCheckError('Failed to Load Enabled Modules.');
    }
  } catch (error) {
    if (error instanceof InstanceCheckError && action === undefined) {
      throw error;
    }
    yield showSnackMessage(
      getMessageAlongWithGenericErrors(
        error,
        'Failed to Load Enabled Modules.',
      ),
      TYPE_ERROR,
    );
    yield put(fetchEnabledModulesFinished(undefined, true));
  } finally {
    if (action) {
      yield closeLoader();
    }
  }
}
Example #26
Source File: sagas.ts    From slice-machine with Apache License 2.0 5 votes vote down vote up
export function* pushCustomTypeSaga() {
  try {
    const currentCustomType = (yield select(
      selectCurrentCustomType
    )) as ReturnType<typeof selectCurrentCustomType>;

    if (!currentCustomType) {
      return;
    }

    yield call(pushCustomType, currentCustomType.id);
    void Tracker.get().trackCustomTypePushed({
      id: currentCustomType.id,
      name: currentCustomType.label || currentCustomType.id,
      type: currentCustomType.repeatable ? "repeatable" : "single",
    });
    yield put(pushCustomTypeCreator.success());
    yield put(
      openToasterCreator({
        message: "Model was correctly saved to Prismic!",
        type: ToasterType.SUCCESS,
      })
    );
  } catch (e) {
    if (axios.isAxiosError(e) && e.response) {
      // Auth error
      if (e.response.status === 403) {
        yield put(modalOpenCreator({ modalKey: ModalKeysEnum.LOGIN }));
        return;
      }
      // Other server errors
      if (e.response.status > 209) {
        yield put(
          openToasterCreator({
            // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment, @typescript-eslint/no-unsafe-member-access
            message: e.response.data.reason,
            type: ToasterType.ERROR,
          })
        );
        return;
      }
    }

    // Unknown errors
    yield put(
      openToasterCreator({
        message: "Internal Error: Custom type not pushed",
        type: ToasterType.ERROR,
      })
    );
  }
}
Example #27
Source File: sagas.ts    From rhub-app with MIT License 5 votes vote down vote up
export default function* load() {
  try {
    const response: Record<string, any> = yield call(api.get, '/cowsay');
    yield put(loadSuccess(response.data));
  } catch (err) {
    yield put(loadFailure());
  }
}