Skip to content

Commit

Permalink
Add control for handling AsyncAction.value in error and revalidatio…
Browse files Browse the repository at this point in the history
…n scenarios
  • Loading branch information
lemonmade committed Oct 15, 2024
1 parent 44b2b93 commit c365777
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changeset/afraid-lions-nail.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@quilted/async': patch
---

Add control for handling `AsyncAction.value` in error and revalidation scenarios
23 changes: 22 additions & 1 deletion packages/async/source/AsyncAction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,19 @@ export class AsyncAction<Data = unknown, Input = unknown> {
}

get value() {
return this.latest?.value ?? this.resolved?.value;
const running = this.running;
const runningValue = running?.value;
if (runningValue !== undefined) return runningValue;

if (!this.#staleWhileRevalidate && running) {
return undefined;
}

if (!this.#staleIfError && this.finished?.error) {
return undefined;
}

return this.resolved?.value;
}

get data() {
Expand Down Expand Up @@ -108,18 +120,25 @@ export class AsyncAction<Data = unknown, Input = unknown> {
lastInput?: Input,
) => boolean;

readonly #staleIfError: boolean;
readonly #staleWhileRevalidate: boolean;

constructor(
fetchFunction: AsyncActionFunction<Data, Input>,
{
cached,
hasChanged = defaultHasChanged,
staleIfError = true,
staleWhileRevalidate = true,
}: {
cached?: AsyncActionRunCache<Data, Input>;
hasChanged?(
this: AsyncAction<Data, Input>,
input?: Input,
lastInput?: Input,
): boolean;
staleIfError?: boolean;
staleWhileRevalidate?: boolean;
} = {},
) {
this.function = fetchFunction;
Expand All @@ -128,6 +147,8 @@ export class AsyncAction<Data = unknown, Input = unknown> {
finally: this.#finalizeAction,
});
this.#hasChanged = hasChanged;
this.#staleIfError = staleIfError;
this.#staleWhileRevalidate = staleWhileRevalidate;
}

run = (
Expand Down

0 comments on commit c365777

Please sign in to comment.