From 6f4230b2fcf21149a1f078047d696caae69d5c47 Mon Sep 17 00:00:00 2001 From: Eric Bower Date: Wed, 2 Aug 2023 15:16:06 -0400 Subject: [PATCH] feat: invalidate cache via action payload ```ts import { timer, InvalidateCachePayload } from 'saga-query'; interface FetchUsersrops extends InvalidateCachePayload { id: string; } const fetchUser = api.get( '/users/:id', { saga: timer() }, ); store.dispatch(fetchUser({ id: '1' })); // pop cache store.dispatch(fetchUser({ id: '1', invalidate: true })); ``` --- src/saga.ts | 12 +++++++++--- src/types.ts | 4 ++++ 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/saga.ts b/src/saga.ts index 15a1585..2f8a40d 100644 --- a/src/saga.ts +++ b/src/saga.ts @@ -74,7 +74,7 @@ export function timer(timer: number = 5 * MINUTES) { saga: any, ...args: any[] ): SagaIterator { - const map: { [key: string]: Task } = {}; + const map: { [key: string]: Task | undefined } = {}; function* activate(action: ActionWithPayload) { yield call(saga, action, ...args); @@ -87,8 +87,14 @@ export function timer(timer: number = 5 * MINUTES) { `${actionType}`, ); const key = action.payload.key; - const notRunning = map[key] && !map[key].isRunning(); - if (!map[key] || notRunning) { + const invalidate = action.payload.options?.invalidate || false; + const foundTask = map[key]; + + const taskNotFound = !foundTask; + const isRunning = foundTask && foundTask.isRunning(); + const shouldInvalidate = !isRunning && invalidate; + + if (taskNotFound || !isRunning || shouldInvalidate) { const task = yield fork(activate, action); map[key] = task; } diff --git a/src/types.ts b/src/types.ts index 22c10ee..85fcb1f 100644 --- a/src/types.ts +++ b/src/types.ts @@ -103,6 +103,10 @@ export interface CreateActionPayload

{ options: P; } +export interface InvalidateCachePayload { + invalidate?: boolean; +} + export type CreateActionFn = () => ActionWithPayload>; export interface CreateAction extends CreateActionFn {