redux-saga/effects#take TypeScript Examples
The following examples show how to use
redux-saga/effects#take.
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: saga.test.ts From react-js-tutorial with MIT License | 6 votes |
describe("Background saga", () => {
it("Background saga flow", () => {
const saga = testSaga(backgroundSaga);
saga
.next()
.take(actions.start.type)
.next()
.race({
task: call(createConnection),
cancel: take(actions.cancel.type),
})
.finish();
});
});
Example #2
Source File: updater.ts From marina with MIT License | 6 votes |
// starts a set of workers in order to handle asynchronously the UPDATE_TASK action
export function* watchUpdateTask(): SagaGenerator<void, UpdateTaskAction> {
const MAX_UPDATER_WORKERS = 3;
const accountToUpdateChan = yield* createChannel<UpdateTaskAction['payload']>();
for (let i = 0; i < MAX_UPDATER_WORKERS; i++) {
yield fork(updaterWorker, accountToUpdateChan);
}
// start the asset updater
const assetsChan = yield* createChannel<{ assetHash: string; network: NetworkString }>();
yield fork(assetsWorker, assetsChan);
yield fork(watchForAddUtxoAction, assetsChan); // this will fee the assets chan
// listen for UPDATE_TASK
while (true) {
const { payload } = yield take(UPDATE_TASK);
yield fork(updateUtxoAssets(assetsChan));
yield put(accountToUpdateChan, payload);
}
}
Example #3
Source File: updater.ts From marina with MIT License | 6 votes |
export function* watchForAddUtxoAction(
chan: Channel<{ assetHash: string; network: NetworkString }>
): SagaGenerator<void, AddUtxoAction> {
while (true) {
const action = yield take(ADD_UTXO);
const asset = getAsset(action.payload.utxo);
if (asset) {
yield put(chan, { assetHash: asset, network: action.payload.network });
}
}
}
Example #4
Source File: updater.ts From marina with MIT License | 6 votes |
function* assetsWorker(
assetsChan: Channel<{ assetHash: string; network: NetworkString }>
): SagaGenerator<void, { assetHash: string; network: NetworkString }> {
while (true) {
const { assetHash, network } = yield take(assetsChan);
if (yield* needUpdate(assetHash)) {
try {
const asset = yield* requestAssetInfoFromEsplora(assetHash, network);
yield put(addAsset(assetHash, asset));
} catch (e) {
console.warn(`Error fetching asset ${assetHash}`, e);
}
}
}
}
Example #5
Source File: updater.ts From marina with MIT License | 6 votes |
function* updaterWorker(
chanToListen: Channel<UpdateTaskAction['payload']>
): SagaGenerator<void, UpdateTaskAction['payload']> {
while (true) {
const { accountID, network } = yield take(chanToListen);
try {
yield put(pushUpdaterLoader());
yield* updateTxsAndUtxos(accountID, network);
} finally {
yield put(popUpdaterLoader());
}
}
}
Example #6
Source File: saga.ts From react-js-tutorial with MIT License | 6 votes |
export function* loginSaga() {
yield fork(checkUserSession);
while (true) {
const action = yield take(actions.login.type);
yield* saveUserSession(action);
yield take(actions.logout.type);
yield* clearUserSession();
}
}
Example #7
Source File: saga.ts From react-js-tutorial with MIT License | 6 votes |
export function* watchFirstThreeAction() {
for (let i = 0; i < 3; i++) {
yield take("*");
// eslint-disable-next-line no-console
console.log(`Action number: #${i}`);
}
// eslint-disable-next-line no-console
console.log("First tree actions done!");
}
Example #8
Source File: saga.ts From react-js-tutorial with MIT License | 6 votes |
export function* watchAndLog() {
while (true) {
const action = yield take("*");
const state = yield select();
// eslint-disable-next-line no-console
console.log("action", action);
// eslint-disable-next-line no-console
console.log("state after", state);
}
}
Example #9
Source File: saga.ts From react-js-tutorial with MIT License | 6 votes |
export function* chatSaga() {
const socket = yield call(createWebSocketConnection);
const socketChannel = yield call(createSocketChannel, socket);
yield takeEvery(actions.send.type, sendMessage, socket);
while (true) {
try {
const payload = yield take(socketChannel);
yield put(actions.update([payload]));
} catch (err) {
console.error("socket error:", err);
socketChannel.close();
}
}
}
Example #10
Source File: saga.ts From react-js-tutorial with MIT License | 6 votes |
export function* backgroundSaga() {
while (true) {
yield take(actions.start.type);
yield race({
task: call(createConnection),
cancel: take(actions.cancel.type),
});
}
}
Example #11
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 #12
Source File: saga.ts From celo-web-wallet with MIT License | 6 votes |
/**
* 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 #13
Source File: watchReplaysAdded.ts From rewind with MIT License | 6 votes |
export function* watchReplaysAdded(url: string): SagaIterator {
console.log("Starting watchReplaysAdded Saga");
const socket = yield call(createWebSocketConnection, url);
const channel = yield call(createSocketChannel, socket);
while (true) {
try {
const payload: Payload = yield take(channel);
// yield put(theaterStageChangeRequested(payload));
} catch (err) {
console.error("Socket error: ", err);
}
}
}
Example #14
Source File: RootSaga.ts From rewind with MIT License | 6 votes |
// TODO: This whole thing should be rewritten
function* waitForBackendState(state: BackendState): SagaIterator {
while (true) {
const action = yield take(stateChanged.type);
if (stateChanged.match(action) && action.payload === state) {
break;
}
}
}
Example #15
Source File: index.ts From FLECT_Amazon_Chime_Meeting with Apache License 2.0 | 6 votes |
function* handleGetAttendeeInfomation(){
while(true){
const action = yield take('GET_ATTENDEE_INFORMATION')
const meetingId = action.payload[0]
const attendeeId = action.payload[1]
const baseAttendeeId = encodeURIComponent(new DefaultModality(attendeeId).base());
const url = `${API_BASE_URL}meetings/${meetingId}/attendees/${baseAttendeeId}`
console.log(meetingId, attendeeId, url)
try{
let data = yield call((url:string) =>{
return fetch(url, {
method: 'GET',
})
.then(res => res.json())
.catch(error => {throw error})
}, url);
console.log("UPDATE_ATTENDEE_INFO", data)
yield put(Actions.updateAttendeeInformation(meetingId, attendeeId, baseAttendeeId, decodeURIComponent(data.AttendeeInfo.UserName)));
}catch(e){
console.log('failed:'+e)
}
}
}
Example #16
Source File: index.ts From FLECT_Amazon_Chime_Meeting with Apache License 2.0 | 6 votes |
function* handleLeaveMeeting() {
while (true) {
const action = yield take('LEAVE_MEETING');
console.log(action)
const meetingId = action.payload[0]
const attendeeId = action.payload[1]
const url = `${API_BASE_URL}meetings/${meetingId}/attendees/${attendeeId}`
console.log(url)
try{
let data = yield call((url:string) =>{
return fetch(url, {
method: 'DELETE',
})
.then(res => res.json())
.catch(error => {throw error})
}, url);
console.log(data)
yield put(Actions.leftMeeting(data));
}catch(e){
console.log('failed:'+e)
}
}
}
Example #17
Source File: index.ts From FLECT_Amazon_Chime_Meeting with Apache License 2.0 | 6 votes |
function* handleJoinMeeting() {
while (true) {
const action = yield take('JOIN_MEETING');
console.log(action)
const meetingId = action.payload[0]
const gs = action.payload[1] as GlobalState
const url = `${API_BASE_URL}meetings/${meetingId}/attendees?userName=${gs.userName}`
console.log(url)
try{
let data = yield call((url:string) =>{
return fetch(url, {
method: 'POST',
})
.then(res => {
if(res.ok){
return res.json()
}else{
throw new Error('Join failed: '+res);
}
})
.catch(error => {
throw error
})
}, url);
console.log(data)
yield put(Actions.joinedMeeting(data));
}catch(e){
yield put(Actions.showError(`Sorry, there is no meeting room! [${meetingId}]`))
yield put(Actions.refreshRoomList())
console.log('failed:'+e)
}
}
}
Example #18
Source File: index.ts From FLECT_Amazon_Chime_Meeting with Apache License 2.0 | 6 votes |
function* handleRefreshRoomList() {
while (true) {
const action = yield take('REFRESH_ROOM_LIST');
console.log(action)
const url = `${API_BASE_URL}meetings`
console.log(url)
try{
let data = yield call((url:string) =>{
return fetch(url, {
method: 'GET',
mode: "cors"
})
.then(res => res.json())
.catch(error => {throw error})
}, url);
console.log(data)
yield put(Actions.gotAllRoomList(data));
}catch(e){
console.log('failed:'+e)
}
}
}
Example #19
Source File: index.ts From FLECT_Amazon_Chime_Meeting with Apache License 2.0 | 6 votes |
function* handleCreateMeeting() {
while (true) {
const action = yield take('CREATE_MEETING');
console.log(action)
const userName = action.payload[0]
const meetingName = action.payload[1]
const region = action.payload[2]
const usePassCode = action.payload[3]
const passCode = action.payload[4]
const secret = action.payload[5]
const userNameEnc = encodeURIComponent(userName)
const meetingNameEnc = encodeURIComponent(meetingName)
const passCodeEnc = encodeURIComponent(passCode)
const url = `${API_BASE_URL}meetings?userName=${userNameEnc}&meetingName=${meetingNameEnc}®ion=${region}`+
`&usePassCode=${usePassCode}&passCode=${passCodeEnc}&secret=${secret}`
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.refreshRoomList());
}catch(e){
console.log('failed:'+e)
}
}
}
Example #20
Source File: api.ts From orangehrm-os-mobile with GNU General Public License v3.0 | 5 votes |
export function* apiCall<Fn extends (...args: any[]) => any>(
fn: Fn,
...args: Parameters<Fn>
) {
let authParams: AuthParams = yield selectAuthParams();
if (authParams.fetchingAccessTokenLock) {
let action: SetFetchingAccessTokenLockAction;
// `task` effect is blocking
while ((action = yield take(SET_FETCHING_ACCESS_TOKEN_LOCK))) {
if (action.state === false) {
// Aquired lock
yield put(setFetchingAccessTokenLock(true));
break;
}
}
// Update auth params to continue after waiting
authParams = yield selectAuthParams();
} else {
// Aquired lock
yield put(setFetchingAccessTokenLock(true));
}
if (isAccessTokenExpired(authParams.expiresAt)) {
if (authParams.refreshToken !== null && authParams.instanceUrl !== null) {
const response: Response = yield call(
getNewAccessToken,
authParams.instanceUrl,
authParams.refreshToken,
);
const data = yield call([response, response.json]);
if (data.access_token) {
yield storageSetMulti({
[ACCESS_TOKEN]: data.access_token,
...(data.refresh_token !== undefined &&
data.refresh_token !== null && {
[REFRESH_TOKEN]: data.refresh_token,
}),
[TOKEN_TYPE]: data.token_type,
[SCOPE]: data.scope,
[EXPIRES_AT]: getExpiredAt(data.expires_in),
});
yield put(fetchNewAuthTokenFinished());
} else {
if (data.error === 'authentication_failed') {
// employee not assigned, terminated, disabled
yield put(logout());
throw new AuthenticationError(data.error_description);
} else if (
data.error === 'invalid_grant' &&
data.error_description === 'Refresh token has expired'
) {
// expire refresh token time
yield put(logout());
throw new AuthenticationError('Authentication Expired');
} else {
throw new AuthenticationError('Authentication Failed');
}
}
} else {
throw new Error("Couldn't call with empty instanceUrl or refreshToken.");
}
}
// Release lock
yield put(setFetchingAccessTokenLock(false));
const result = yield call(fn, ...args);
return result;
}
Example #21
Source File: index.ts From slice-machine with Apache License 2.0 | 5 votes |
// Sagas
function* checkSetupSaga(
action: ReturnType<typeof checkSimulatorSetupCreator.request>
) {
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const { data: setupStatus }: { data: SimulatorCheckResponse } = yield call(
checkSimulatorSetup
);
// All the backend checks are ok ask for the frontend Iframe check
if ("ok" === setupStatus.manifest && "ok" === setupStatus.dependencies) {
yield put(
checkSimulatorSetupCreator.success({
setupStatus: { iframe: null, ...setupStatus },
})
);
yield put(connectToSimulatorIframeCreator.request());
// eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
const {
timeout,
iframeCheckKO,
iframeCheckOk,
}: {
iframeCheckOk: ReturnType<
typeof connectToSimulatorIframeCreator.success
>;
iframeCheckKO: ReturnType<
typeof connectToSimulatorIframeCreator.failure
>;
timeout: CallEffect<true>;
} = yield race({
iframeCheckOk: take(getType(connectToSimulatorIframeCreator.success)),
iframeCheckKO: take(getType(connectToSimulatorIframeCreator.failure)),
timeout: delay(10000),
});
if (iframeCheckOk && action.payload.callback) {
action.payload.callback();
return;
}
if (timeout) {
yield put(connectToSimulatorIframeCreator.failure());
yield call(failCheckSetupSaga);
return;
}
if (iframeCheckKO) {
yield call(failCheckSetupSaga);
return;
}
return;
}
// All the backend checks are ko and the request is coming from the "start"
const isTheFirstTime =
"ko" === setupStatus.manifest &&
"ko" === setupStatus.dependencies &&
action.payload.withFirstVisitCheck;
if (isTheFirstTime) {
yield put(openSetupDrawerCreator({}));
return;
}
yield put(
checkSimulatorSetupCreator.success({
setupStatus: { iframe: null, ...setupStatus },
})
);
yield call(failCheckSetupSaga);
} catch (error) {
// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
yield put(checkSimulatorSetupCreator.failure(error as Error));
}
}
Example #22
Source File: index.ts From FLECT_Amazon_Chime_Meeting with Apache License 2.0 | 5 votes |
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 #23
Source File: saga.ts From celo-web-wallet with MIT License | 4 votes |
/**
* A convenience utility to create a wrapped saga that handles common concerns like
* trigger watching, cancel watching, timeout, progress updates, and success/fail updates.
* Use to create complex sagas that need more coordination with the UI.
* Note: the wrapped saga and reducer this returns must be added to rootSaga.ts
*/
export function createMonitoredSaga<SagaParams = void>(
saga: (params: SagaParams) => any,
name: string,
options?: MonitoredSagaOptions
) {
const triggerAction = createAction<SagaParams>(`${name}/trigger`)
const cancelAction = createAction<void>(`${name}/cancel`)
const statusAction = createAction<SagaStatus>(`${name}/progress`)
const errorAction = createAction<string>(`${name}/error`)
const resetAction = createAction<void>(`${name}/reset`)
const reducer = createReducer<SagaState>({ status: null, error: null }, (builder) =>
builder
.addCase(statusAction, (state, action) => {
state.status = action.payload
state.error = null
})
.addCase(errorAction, (state, action) => {
state.status = SagaStatus.Failure
state.error = action.payload
})
.addCase(resetAction, (state) => {
state.status = null
state.error = null
})
)
const wrappedSaga = function* () {
while (true) {
try {
const trigger: Effect = yield take(triggerAction.type)
logger.debug(`${name} triggered`)
yield put(statusAction(SagaStatus.Started))
const { result, cancel, timeout } = yield race({
// Note: Use fork here instead if parallelism is required for the saga
result: call(saga, trigger.payload),
cancel: take(cancelAction.type),
timeout: delay(options?.timeoutDuration || DEFAULT_TIMEOUT),
})
if (cancel) {
logger.debug(`${name} canceled`)
yield put(errorAction('Action was cancelled.'))
continue
}
if (timeout) {
logger.warn(`${name} timed out`)
yield put(errorAction('Action timed out.'))
continue
}
if (result === false) {
logger.warn(`${name} returned failure result`)
yield put(errorAction('Action returned failure result.'))
continue
}
yield put(statusAction(SagaStatus.Success))
logger.debug(`${name} finished`)
} catch (error: any) {
logger.error(`${name} error`, error)
yield put(errorAction(errorToString(error)))
}
}
}
return {
name,
wrappedSaga,
reducer,
actions: {
trigger: triggerAction,
cancel: cancelAction,
progress: statusAction,
error: errorAction,
reset: resetAction,
},
}
}