Skip to content

Commit

Permalink
fix: reset loader when task is cancelled (#40)
Browse files Browse the repository at this point in the history
This issue happens when:
- User runs a task with a loader
- Loading is in "loading" state
- Task gets halted
- Loader does not get cleaned up
- Loader stays in "loading" state
  • Loading branch information
neurosnap committed Feb 22, 2024
1 parent c18cc7e commit 072dd5b
Showing 1 changed file with 50 additions and 32 deletions.
82 changes: 50 additions & 32 deletions store/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,14 @@ export function loader<
message: err.message,
}),
]);
} finally {
const loaders = yield* select((s: any) =>
loaderSchema.selectByIds(s, { ids: [ctx.name, ctx.key] })
);
const ids = loaders
.filter((loader) => loader.status === "loading")
.map((loader) => loader.id);
yield* updateStore(loaderSchema.resetByIds(ids));
}
};
}
Expand All @@ -112,44 +120,54 @@ export function loaderApi<
},
) {
return function* trackLoading(ctx: Ctx, next: Next) {
yield* updateStore([
loaderSchema.start({ id: ctx.name }),
loaderSchema.start({ id: ctx.key }),
]);
if (!ctx.loader) ctx.loader = {} as any;
try {
yield* updateStore([
loaderSchema.start({ id: ctx.name }),
loaderSchema.start({ id: ctx.key }),
]);
if (!ctx.loader) ctx.loader = {} as any;

yield* next();
yield* next();

if (!ctx.response) {
yield* updateStore(
loaderSchema.resetByIds([ctx.name, ctx.key]),
);
return;
}
if (!ctx.response) {
yield* updateStore(
loaderSchema.resetByIds([ctx.name, ctx.key]),
);
return;
}

if (!ctx.loader) {
ctx.loader = {};
}
if (!ctx.loader) {
ctx.loader = {};
}

if (!ctx.response.ok) {
yield* updateStore([
loaderSchema.error({
id: ctx.name,
message: errorFn(ctx),
...ctx.loader,
}),
loaderSchema.error({
id: ctx.key,
message: errorFn(ctx),
...ctx.loader,
}),
]);
return;
}

if (!ctx.response.ok) {
yield* updateStore([
loaderSchema.error({
id: ctx.name,
message: errorFn(ctx),
...ctx.loader,
}),
loaderSchema.error({
id: ctx.key,
message: errorFn(ctx),
...ctx.loader,
}),
loaderSchema.success({ id: ctx.name, ...ctx.loader }),
loaderSchema.success({ id: ctx.key, ...ctx.loader }),
]);
return;
} finally {
const loaders = yield* select((s: any) =>
loaderSchema.selectByIds(s, { ids: [ctx.name, ctx.key] })
);
const ids = loaders
.filter((loader) => loader.status === "loading")
.map((loader) => loader.id);
yield* updateStore(loaderSchema.resetByIds(ids));
}

yield* updateStore([
loaderSchema.success({ id: ctx.name, ...ctx.loader }),
loaderSchema.success({ id: ctx.key, ...ctx.loader }),
]);
};
}

0 comments on commit 072dd5b

Please sign in to comment.