redux-saga/effects#put TypeScript Examples
The following examples show how to use
redux-saga/effects#put.
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: sagas.ts From generator-earth with MIT License | 6 votes |
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 #2
Source File: index.ts From FLECT_Amazon_Chime_Meeting with Apache License 2.0 | 6 votes |
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 #3
Source File: RootSaga.ts From rewind with MIT License | 6 votes |
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 #4
Source File: index.ts From camus with GNU Affero General Public License v3.0 | 6 votes |
function* doSetUsername({ payload }: PayloadAction<string>) {
const manager: Manager = yield getContext('manager');
const username = payload;
try {
yield apply(manager, manager.setUsername, [username]);
yield put({ type: 'MANAGER_UPDATED' });
} catch (err) {
yield put({ type: 'MANAGER_ERROR', payload: err });
}
}
Example #5
Source File: sagas.ts From firebase-tools-ui with Apache License 2.0 | 6 votes |
// 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 #6
Source File: Checkout.saga.ts From react-native-woocommerce with MIT License | 6 votes |
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 #7
Source File: newsFeedSaga.ts From foodie with MIT License | 6 votes |
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 #8
Source File: saga.ts From mamori-i-japan-admin-panel with BSD 2-Clause "Simplified" License | 6 votes |
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 #9
Source File: saga.test.ts From react-js-tutorial with MIT License | 6 votes |
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 #10
Source File: sagas.ts From orangehrm-os-mobile with GNU General Public License v3.0 | 6 votes |
function* fetchConfigHelp(action: FetchHelpConfigAction) {
try {
yield openLoader();
const response = yield apiCall(
apiGetCall,
prepare(
API_ENDPOINT_HELP_CONFIG,
{},
{
query: action.payload.query,
mode: action.payload.mode,
},
),
);
if (response.data) {
yield put(fetchHelpConfigFinished(response.data));
} else {
yield showSnackMessage(
getMessageAlongWithResponseErrors(
response,
'Failed to Fetch Help Configurations',
),
TYPE_ERROR,
);
}
} catch (error) {
yield showSnackMessage(
getMessageAlongWithGenericErrors(
error,
'Failed to Fetch Help Configurations.',
),
TYPE_ERROR,
);
} finally {
yield closeLoader();
}
}
Example #11
Source File: user-saga.ts From Riakuto-StartingReact-ja3.1 with Apache License 2.0 | 6 votes |
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 #12
Source File: index.ts From slice-machine with Apache License 2.0 | 6 votes |
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 #13
Source File: saga.ts From react-boilerplate-cra-template with MIT License | 6 votes |
/**
* 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 #14
Source File: sagas.ts From rhub-app with MIT License | 6 votes |
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 #15
Source File: sagas.ts From waifusion-site with MIT License | 6 votes |
/* ACTIONS */
function* loadWaifusAction() {
const waifus: Waifu[] = yield select(selectWaifus);
const waifusCopy = [...waifus];
const contractHelper = new ContractHelper();
yield contractHelper.init();
const _ownedWaifus: Waifu[] = yield contractHelper.getWaifus();
yield put(setWaifuIndexes(_ownedWaifus.map((waifu: Waifu) => waifu.id)));
for (let i = 0; i < _ownedWaifus.length; i++) {
const waifuIds = waifus.map((waifu: Waifu) => waifu.id);
if (waifuIds.indexOf(_ownedWaifus[i].id) === -1)
waifusCopy.push(_ownedWaifus[i]);
else waifusCopy[i] = _ownedWaifus[i];
}
waifusCopy.reverse();
yield put(setWaifus(waifusCopy));
yield put(completeLoadWaifus());
}
Example #16
Source File: deep-restorer.ts From marina with MIT License | 6 votes |
// restoreAllAccounts will launch a deep restore for each account in the redux state
// it will restore the account for the current selected network (the one set in redux state)
// then it will update the restorerOpts in the state after restoration
function* restoreAllAccounts(): SagaGenerator {
const isRunning = yield* selectDeepRestorerIsLoadingSaga();
if (isRunning) return;
yield put(setDeepRestorerIsLoading(true));
try {
const gapLimit = yield* selectDeepRestorerGapLimitSaga();
const esploraURL = yield* selectExplorerSaga();
const accountsIDs = yield* selectAllAccountsIDsSaga();
for (const ID of accountsIDs) {
const network = yield* selectNetworkSaga();
const stateRestorerOpts = yield* deepRestore(ID, gapLimit, esploraURL, network);
yield put(setRestorerOpts(ID, stateRestorerOpts, network)); // update state with new restorerOpts
yield put(updateTaskAction(ID, network)); // update utxos and transactions according to the restored addresses (on network)
}
yield put(setDeepRestorerError(undefined));
} catch (e) {
yield put(setDeepRestorerError(new Error(extractErrorMessage(e))));
} finally {
yield put(setDeepRestorerIsLoading(false));
}
}