Skip to content

Commit

Permalink
fix behavior with strict mode
Browse files Browse the repository at this point in the history
  • Loading branch information
dai-shi committed Jan 9, 2024
1 parent a243b8c commit 480a053
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 34 deletions.
8 changes: 6 additions & 2 deletions examples/01_typescript/src/index.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
import React from 'react';
import React, { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';

import App from './App';

const ele = document.getElementById('app');
if (ele) {
createRoot(ele).render(<App />);
createRoot(ele).render(
<StrictMode>
<App />
</StrictMode>,
);
}
51 changes: 19 additions & 32 deletions src/atomWithCache.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { atom } from 'jotai/vanilla';
import type { Atom, Getter } from 'jotai/vanilla';
import type { Atom, Getter, WritableAtom } from 'jotai/vanilla';

type AnyAtomValue = unknown;
type AnyAtom = Atom<AnyAtomValue>;
Expand Down Expand Up @@ -29,27 +29,24 @@ export function atomWithCache<Value>(
writeGetterAtom.debugPrivate = true;
}

const baseAtom = atom(
(get, opts) => {
const writeGetter = get(writeGetterAtom)?.[0];
if (writeGetter) {
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);
}),
);
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;
const baseAtom: WritableAtom<Value, [AnyAtom], AnyAtomValue> = atom(
(get, { setSelf: writeGetter, ...opts }) => {
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);
}),
);
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;
}
}
const map = new Map<AnyAtom, AnyAtomValue>();
Expand All @@ -64,23 +61,13 @@ export function atomWithCache<Value>(
}
return value;
},
(get, set, isInit) => {
if (isInit) {
set(writeGetterAtom, [get]);
} else {
set(writeGetterAtom, null);
}
},
(get, _set, anAtom: AnyAtom) => get(anAtom), // HACK HACK HACK
);

if (process.env.NODE_ENV !== 'production') {
baseAtom.debugPrivate = true;
}

baseAtom.onMount = (init) => {
init(true);
return () => init(false);
};
const derivedAtom = atom((get) => get(baseAtom));
return derivedAtom;
}

0 comments on commit 480a053

Please sign in to comment.