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

feat: Make store set async and accept promise as arg #6

Merged
merged 1 commit into from
Nov 23, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion src/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,12 @@ export class Store<T> {
this.subscribers = new Set();
}

set(newValue: T | CurrentValueCallback, options: SetOptions = { filter: () => true }) {
async set(newValue: T | CurrentValueCallback | Promise<T | CurrentValueCallback>, options: SetOptions = { filter: () => true }) {
// Consider enriching the store value with some kind of typing similar to Stimulus values typing.
// This would provide type safety and autocompletion benefits when working with the store value.
// It would also make the code more self-documenting, as the types would provide information about what kind of values are expected.
// This could be achieved by using TypeScript generics or by defining specific types for different kinds of store values.
if (newValue instanceof Promise) return this.resolvePromise(newValue, options);
if (newValue === this.get()) return;
this.value = typeof newValue === "function" ? (newValue as CurrentValueCallback)(this.value) : newValue;
this.notifySubscribers(options);
Expand All @@ -68,4 +69,13 @@ export class Store<T> {
.filter(() => options.filter(this.value))
.forEach(callback => callback(this.value))
}

private async resolvePromise(newValue: Promise<T | CurrentValueCallback>, options: SetOptions) {
try {
const resolvedValue = await newValue;
this.set(resolvedValue, options);
} catch (error) {
console.error('Failed to resolve promise:', error);
}
}
}