Skip to content

Commit

Permalink
fix: always async
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi committed Jan 11, 2024
1 parent 6c948e2 commit 1b6427b
Showing 1 changed file with 11 additions and 13 deletions.
24 changes: 11 additions & 13 deletions src/atomWithCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,33 +20,31 @@ type Options = {
export function atomWithCache<Value>(
read: Read<Value>,
options?: Options,
): Atom<Value> {
): Atom<Promise<Awaited<Value>>> {
const is = options?.areEqual || Object.is;
// this cache is common across Provider components
const cache: [CreatedAt, AnyAtomValue, Map<AnyAtom, AnyAtomValue>][] = [];
const cache: [CreatedAt, Awaited<Value>, Map<AnyAtom, AnyAtomValue>][] = [];

const baseAtom: WritableAtom<Value, [AnyAtom], AnyAtomValue> = atom(
(get, { setSelf: writeGetter, ...opts }) => {
const baseAtom: WritableAtom<
Promise<Awaited<Value>>,
[AnyAtom],
AnyAtomValue
> = atom(
async (get, { setSelf: writeGetter, ...opts }): Promise<Awaited<Value>> => {
const index = cache.findIndex((item) =>
Array.from(item[2]).every(([a, v]) => {
const vv = writeGetter(a);
if (vv instanceof Promise) {
return false;
}
return is(v, vv);
}),
Array.from(item[2]).every(([a, v]) => is(v, writeGetter(a))),
);
if (index >= 0) {
const item = cache[index] as (typeof cache)[number];
if (options?.shouldRemove?.(...item)) {
cache.splice(index, 1);
} else {
item[2].forEach((_, a) => get(a)); // touch atoms
return item[1] as Value;
return item[1] as Awaited<Value>;
}
}
const map = new Map<AnyAtom, AnyAtomValue>();
const value = read(
const value = await read(
(a) => {
const v = get(a);
map.set(a, v);
Expand Down

0 comments on commit 1b6427b

Please sign in to comment.