Skip to content

fix(core): handle an edge case of changing dependencies without changing atom value #960

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Jan 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions src/core/store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -349,6 +349,17 @@ export const createStore = (
if (nextAtomState.d.has(atom)) {
nextAtomState.d = new Map(nextAtomState.d).set(atom, nextAtomState.r)
}
} else if (
nextAtomState.d !== atomState.d &&
(nextAtomState.d.size !== atomState.d.size ||
!Array.from(nextAtomState.d.keys()).every((a) => atomState.d.has(a)))
) {
// value is not changed, but dependencies are changed
// we should schdule a flush in async
// FIXME any better way? https://github.com/pmndrs/jotai/issues/947
Promise.resolve().then(() => {
flushPending(version)
})
}
setAtomState(version, atom, nextAtomState)
return nextAtomState
Expand Down
34 changes: 34 additions & 0 deletions tests/basic.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -269,6 +269,40 @@ it('only re-renders if value has changed', async () => {
})
})

it('re-renders a time delayed derived atom with the same initial value (#947)', async () => {
const aAtom = atom(false)
aAtom.onMount = (set) => {
setTimeout(() => {
set(true)
})
}

const bAtom = atom(1)
bAtom.onMount = (set) => {
set(2)
}

const cAtom = atom((get) => {
if (get(aAtom)) {
return get(bAtom)
}
return 1
})

const App = () => {
const [value] = useAtom(cAtom)
return <>{value}</>
}

const { findByText } = render(
<Provider>
<App />
</Provider>
)

await findByText('2')
})

it('works with async get', async () => {
const countAtom = atom(0)
const asyncCountAtom = atom(async (get) => {
Expand Down