Skip to content

Commit

Permalink
AL: fix linking bug
Browse files Browse the repository at this point in the history
  • Loading branch information
adalundhe committed Feb 25, 2024
1 parent 2fd8c03 commit e7ea8f9
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 15 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "delta-state",
"version": "1.1.5",
"version": "1.1.6",
"description": "A modern version of the Delta state manager - written for TS and with the use of React Hooks.",
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
Expand Down
37 changes: 23 additions & 14 deletions src/react.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,35 +42,44 @@ const createImpl = <T extends StoreApi<T>>(store: Store<T>, init: T) => {
export const useAtom = <T>(
atom: T,
update: (set: (next: T) => T) => (next: T) => T | Promise<T>,
link?: (source: T, local: T) => T,
link?: (source: T, local: T) => T
) => {
const atomStore = useRef(new Atom(atom)).current;

const lastLinkedState = useRef(atom);
const atomStore = useRef(
new Atom(atom)
).current;

const set = (next: T) => {
atomStore.value = next;
atomStore.subscribers.forEach((callback) => callback());
return next;
};
const lastLinkedState = useRef(atom)


const set = (next :T) => {
atomStore.value = next
atomStore.subscribers.forEach((callback) => callback())
return next
}

const setUpdate = update(set);
const setUpdate = update(set)

useMemo(() => {
if (lastLinkedState.current !== atom && link) {
lastLinkedState.current = atom;
atomStore.value = link(lastLinkedState.current, atomStore.value);
if (lastLinkedState.current !== atom && link){
lastLinkedState.current = atom
atomStore.value = link(lastLinkedState.current, atomStore.value)
}

}, [atom, atomStore, link]);


return [
useSyncExternalStore(
(callback) => atomStore.subscribe(callback),
() => atomStore.getState(),
() => atomStore.getState(),
),
setUpdate,
] as [T, typeof setUpdate];
setUpdate
] as [
T,
typeof setUpdate
]
};

const createAtomImpl = <T>(
Expand Down

0 comments on commit e7ea8f9

Please sign in to comment.