Skip to content

Commit

Permalink
feat: Store the updater first to avoid data update failure in extreme…
Browse files Browse the repository at this point in the history
… cases
  • Loading branch information
cceevv committed Jun 19, 2023
1 parent 7ab4847 commit dd4c8f9
Showing 1 changed file with 16 additions and 14 deletions.
30 changes: 16 additions & 14 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,9 +43,25 @@ export default function tinyStore<S extends {}, A>(

const useStore = (source: boolean) => {
const [, setState] = useState({})
const updaterRef = useRef<Updater<S>>()
const stateProxy = useRef<Partial<S>>({})
const stateCache = useRef<Partial<S>>({})

if (!updaterRef.current) {
updaterRef.current = (data: Partial<S>) => {
for (let key in data) {
if (key in stateCache.current && !equal(data[key], stateCache.current[key])) {
setState({}); break;
}
}
}
hooks.push(updaterRef.current)
}

useEffect(() => () => {
updaterRef.current && hooks.splice(hooks.indexOf(updaterRef.current), 1)
}, [])

useMemo(() => {
stateProxy.current = new Proxy({}, {
get: (_, key: string) => {
Expand All @@ -60,20 +76,6 @@ export default function tinyStore<S extends {}, A>(
})
}, [])

useEffect(() => {
const updater: Updater<S> = (data: Partial<S>) => {
for (let key in data) {
if (key in stateCache.current && !equal(data[key], stateCache.current[key])) {
setState({}); break;
}
}
}
hooks.push(updater)
return () => {
hooks.splice(hooks.indexOf(updater), 1)
}
}, [])

return stateProxy.current
}

Expand Down

0 comments on commit dd4c8f9

Please sign in to comment.