UNPKG

create-async-saga

Version:

Like readux-toolkit's createAsyncThunk, but for saga

37 lines (36 loc) 1.51 kB
import { createAsyncSagaActions } from "./tools/actions"; import { put } from "redux-saga/effects"; import { ConditionError, toSerializedError } from "./tools/error"; export function createAsyncSaga(typePrefix, payloadCreator, options) { const { action, pending, fulfilled, rejected } = createAsyncSagaActions(typePrefix); const canExecute = canExecuteHof(options === null || options === void 0 ? void 0 : options.condition); const asyncSaga = function* ({ payload, meta }) { const requestId = meta.requestId; const execute = yield* canExecute(payload); if (!execute) { if (options === null || options === void 0 ? void 0 : options.dispatchConditionRejection) { yield put(rejected(payload, requestId, new ConditionError())); } return; } yield put(pending(payload, meta.requestId)); try { const result = yield* payloadCreator(payload); yield put(fulfilled(payload, requestId, result)); } catch (err) { const serializedError = toSerializedError(err, typePrefix); yield put(rejected(payload, requestId, serializedError)); } }; return { actionType: action.type, action, pending, fulfilled, rejected, asyncSaga, }; } function canExecuteHof(condition) { return function* (arg) { return condition !== undefined ? yield* condition(arg) : true; }; }