Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Howto wrap takeLatest/takeEvery with solution #653

Open
jochumdev opened this issue Apr 12, 2022 · 0 comments
Open

Howto wrap takeLatest/takeEvery with solution #653

jochumdev opened this issue Apr 12, 2022 · 0 comments

Comments

@jochumdev
Copy link

jochumdev commented Apr 12, 2022

Hey,

I have the need to enable/disable a preloader on all saga calls, after a while I found the following solution for takeEvery/takeLatest in Typescript.

import {
  put,
  takeLatest as upstreamTakeLatest,
  SagaGenerator,
  takeEvery as upstreamTakeEvery,
} from "typed-redux-saga";
import { ActionPattern, ForkEffect } from "redux-saga/effects";
import { ActionMatchingPattern } from "@redux-saga/types";
import { ConfigModule } from "../..";

export const workerWrapper = <P extends ActionPattern>(
  type: P,
  worker: (action: ActionMatchingPattern<P>) => any
): ((action: ActionMatchingPattern<P>) => any) =>
  function* wrapped(action: ActionMatchingPattern<P>): any {
    yield* put(ConfigModule.actions.setPreloader(true));
    try {
      // Call the worker / wrapped action
      yield* worker(action);
    } finally {
      yield* put(ConfigModule.actions.setPreloader(false));
    }
  };

export function takeLatest<P extends ActionPattern>(
  pattern: P,
  worker: (action: ActionMatchingPattern<P>) => any
): SagaGenerator<never, ForkEffect<never>> {
  return upstreamTakeLatest(pattern, workerWrapper(pattern, worker));
}

export function takeEvery<P extends ActionPattern>(
  pattern: P,
  worker: (action: ActionMatchingPattern<P>) => any
): SagaGenerator<never, ForkEffect<never>> {
  return upstreamTakeEvery(pattern, workerWrapper(pattern, worker));
}

I'm posting here with the hope it helps someone else.

Kind regards,
René

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant