Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

preloadSnapshot.ts

23 lines593 Bytes

1export function createPreloadSnapshot<T>(readInitial: () => T, readLatest: () => Promise<T>) {
2 let snapshot: { readonly value: T } | undefined;
3 let pending: Promise<T> | undefined;
4​
5 return {
6 read: () => {
7 snapshot ??= { value: readInitial() };
8 return snapshot.value;
9 },
10 refresh: () => {
11 if (pending !== undefined) return pending;
12 pending = readLatest()
13 .then((value) => {
14 snapshot = { value };
15 return value;
16 })
17 .finally(() => {
18 pending = undefined;
19 });
20 return pending;
21 },
22 };