Skip to content

Commit

Permalink
feat: invalidate cache via action payload
Browse files Browse the repository at this point in the history
```ts
import { timer, InvalidateCachePayload } from 'saga-query';

interface FetchUsersrops extends InvalidateCachePayload {
  id: string;
}

const fetchUser = api.get<FetchUserProps>(
  '/users/:id',
  { saga: timer() },
);

store.dispatch(fetchUser({ id: '1' }));
// pop cache
store.dispatch(fetchUser({ id: '1', invalidate: true }));
```
  • Loading branch information
neurosnap committed Aug 2, 2023
1 parent 8a1c8de commit 6f4230b
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
12 changes: 9 additions & 3 deletions src/saga.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ export function timer(timer: number = 5 * MINUTES) {
saga: any,
...args: any[]
): SagaIterator<void> {
const map: { [key: string]: Task } = {};
const map: { [key: string]: Task | undefined } = {};

function* activate(action: ActionWithPayload<CreateActionPayload>) {
yield call(saga, action, ...args);
Expand All @@ -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;
}
Expand Down
4 changes: 4 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ export interface CreateActionPayload<P = any> {
options: P;
}

export interface InvalidateCachePayload {
invalidate?: boolean;
}

export type CreateActionFn = () => ActionWithPayload<CreateActionPayload<{}>>;

export interface CreateAction<Ctx> extends CreateActionFn {
Expand Down

0 comments on commit 6f4230b

Please sign in to comment.