UNPKG

568 BJavaScriptView Raw
1import { atom } from 'jotai';
2
3function atomWithStore(store) {
4 const baseAtom = atom(store.getState());
5 baseAtom.onMount = (setValue) => {
6 const callback = () => {
7 setValue(store.getState());
8 };
9 const unsub = store.subscribe(callback);
10 callback();
11 return unsub;
12 };
13 const derivedAtom = atom(
14 (get) => get(baseAtom),
15 (get, _set, update) => {
16 const newState = typeof update === "function" ? update(get(baseAtom)) : update;
17 store.setState(newState, true);
18 }
19 );
20 return derivedAtom;
21}
22
23export { atomWithStore };