Skip to content

Commit

Permalink
fix: atomFamily useReducer stale value
Browse files Browse the repository at this point in the history
  • Loading branch information
Aslemammad committed Oct 6, 2021
1 parent 69f66fe commit 1c6e8b1
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/core/useAtom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,8 @@ export function useAtom<Value, Update>(
const ScopeContext = getScopeContext(scope)
const store = useContext(ScopeContext).s

const getAtomValue = useCallback(() => {
const atomState = store[READ_ATOM](atom)
function getAtomValue(_: any, action: typeof atom): Value {
const atomState = store[READ_ATOM](action)
if ('e' in atomState) {
throw atomState.e // read error
}
Expand All @@ -70,13 +70,19 @@ export function useAtom<Value, Update>(
return atomState.v as Value
}
throw new Error('no atom value')
}, [store, atom])
}

const [value, forceUpdate] = useReducer(getAtomValue, undefined, getAtomValue)
const [value, forceUpdate] = useReducer(
getAtomValue,
getAtomValue(null, atom)
)

useEffect(() => {
const unsubscribe = store[SUBSCRIBE_ATOM](atom, forceUpdate)
forceUpdate()
const unsubscribe = store[SUBSCRIBE_ATOM](
atom,
() => forceUpdate(atom)
)
forceUpdate(atom)
return unsubscribe
}, [store, atom])

Expand Down

0 comments on commit 1c6e8b1

Please sign in to comment.