Skip to content

Commit

Permalink
fix: readAtomState in write/get too (pmndrs#298)
Browse files Browse the repository at this point in the history
* add failing test

* fix: readAtomState in write/get too
  • Loading branch information
dai-shi authored Feb 15, 2021
1 parent 82c9fdf commit 0701416
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 11 deletions.
25 changes: 14 additions & 11 deletions src/core/vanilla.ts
Original file line number Diff line number Diff line change
Expand Up @@ -407,34 +407,37 @@ const writeAtomState = <Value, Update>(
try {
const promiseOrVoid = atom.write(
((a: AnyAtom) => {
const aState = getAtomState(nextState, a)
if (!aState) {
if (hasInitialValue(a)) {
return a.init
}
// We pass dummy updateState and throw away nextState.
// There might be a better implementation.
const [aState] = readAtomState(nextState, () => {}, a)
if (aState.re) {
throw aState.re // read error
}
if (aState.rp) {
if (
typeof process === 'object' &&
process.env.NODE_ENV !== 'production'
) {
console.warn(
'Unable to read an atom without initial value in write function. Please useAtom in advance.',
'Reading pending atom state in write operation. We throw a promise for now.',
a
)
}
throw new Error('uninitialized atom')
throw aState.rp // read promise
}
if ('v' in aState) {
return aState.v
}
if (
aState.rp &&
typeof process === 'object' &&
process.env.NODE_ENV !== 'production'
) {
// TODO will try to detect this
console.warn(
'Reading pending atom state in write operation. We need to detect this and fallback. Please file an issue with repro.',
'[Bug] no value found while reading atom in write operation. This probably a bug.',
a
)
}
return aState.v
throw new Error('no value found')
}) as Getter,
((a: AnyWritableAtom, v: unknown) => {
if (a === atom) {
Expand Down
33 changes: 33 additions & 0 deletions tests/dependency.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -345,3 +345,36 @@ it('derived atom to update base atom in callback', async () => {
fireEvent.click(getByText('button'))
await findByText('commits: 2, count: 2, doubled: 4')
})

it('can read sync derived atom in write without initializing', async () => {
const countAtom = atom(1)
const doubledAtom = atom((get) => get(countAtom) * 2)
const addAtom = atom(null, (get, set, num: number) => {
set(countAtom, get(doubledAtom) / 2 + num)
})

const Counter: React.FC = () => {
const [count] = useAtom(countAtom)
const [, add] = useAtom(addAtom)
return (
<>
<div>count: {count}</div>
<button onClick={() => add(1)}>button</button>
</>
)
}

const { getByText, findByText } = render(
<Provider>
<Counter />
</Provider>
)

await findByText('count: 1')

fireEvent.click(getByText('button'))
await findByText('count: 2')

fireEvent.click(getByText('button'))
await findByText('count: 3')
})

0 comments on commit 0701416

Please sign in to comment.