-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathcreateAsync.ts
More file actions
99 lines (91 loc) · 2.58 KB
/
createAsync.ts
File metadata and controls
99 lines (91 loc) · 2.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
/**
* Wrapper around Solid 2.0 async createMemo.
*
* In Solid 2.0, createMemo can return a Promise and the reactive graph
* handles suspension automatically. `createAsync` is therefore a thin
* wrapper that feeds the user-supplied async function into createMemo
* and exposes a `.latest` convenience property.
*/
import { createMemo, latest as solidLatest } from "solid-js";
export type AccessorWithLatest<T> = {
(): T;
latest: T;
};
/** Options for store reconciliation in Solid 2.0 */
export interface ReconcileOptions {
key?: string | ((item: any) => any);
merge?: boolean;
}
export function createAsync<T>(
fn: (prev: T) => Promise<T>,
options: {
name?: string;
initialValue: T;
deferStream?: boolean;
}
): AccessorWithLatest<T>;
export function createAsync<T>(
fn: (prev: T | undefined) => Promise<T>,
options?: {
name?: string;
initialValue?: T;
deferStream?: boolean;
}
): AccessorWithLatest<T | undefined>;
export function createAsync<T>(
fn: (prev: T | undefined) => Promise<T>,
options?: {
name?: string;
initialValue?: T;
deferStream?: boolean;
}
): AccessorWithLatest<T | undefined> {
// In Solid 2.0, createMemo natively handles Promises.
// The memo suspends until the promise resolves; <Loading> catches it.
const memo = createMemo(() => fn(undefined));
const resultAccessor: AccessorWithLatest<T> = (() => memo()) as any;
Object.defineProperty(resultAccessor, "latest", {
get() {
return solidLatest(memo);
}
});
return resultAccessor;
}
export function createAsyncStore<T>(
fn: (prev: T) => Promise<T>,
options: {
name?: string;
initialValue: T;
deferStream?: boolean;
reconcile?: ReconcileOptions;
}
): AccessorWithLatest<T>;
export function createAsyncStore<T>(
fn: (prev: T | undefined) => Promise<T>,
options?: {
name?: string;
initialValue?: T;
deferStream?: boolean;
reconcile?: ReconcileOptions;
}
): AccessorWithLatest<T | undefined>;
export function createAsyncStore<T>(
fn: (prev: T | undefined) => Promise<T>,
options: {
name?: string;
initialValue?: T;
deferStream?: boolean;
reconcile?: ReconcileOptions;
} = {}
): AccessorWithLatest<T | undefined> {
// Derived store form: createStore(fn) in Solid 2.0 creates a projection.
// For now, fall back to the same async memo approach.
const memo = createMemo(() => fn(undefined));
const resultAccessor: AccessorWithLatest<T> = (() => memo()) as any;
Object.defineProperty(resultAccessor, "latest", {
get() {
return solidLatest(memo);
}
});
return resultAccessor;
}