Skip to content
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

fix(vanilla): deal with promise resolving race condition #2199

Merged
merged 6 commits into from
Oct 23, 2023
Merged
Changes from 1 commit
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
145 changes: 142 additions & 3 deletions tests/react/async.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@ import { StrictMode, Suspense, useEffect, useRef } from 'react'
import { act, fireEvent, render, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { expect, it } from 'vitest'
import { useAtom } from 'jotai/react'
import { atom } from 'jotai/vanilla'
import type { Atom } from 'jotai/vanilla'
import { Provider, useAtom } from 'jotai/react'
import { atom, createStore } from 'jotai/vanilla'
import type { Atom, SetStateAction, Setter } from 'jotai/vanilla'

const useCommitCount = () => {
const commitCountRef = useRef(1)
Expand Down Expand Up @@ -1143,3 +1143,142 @@ it('multiple derived atoms with dependency chaining and async write (#813)', asy
getByText('bName: beta')
})
})

it('[render] resolves dependencies reliably after a delay', async () => {
dmaskasky marked this conversation as resolved.
Show resolved Hide resolved
expect.assertions(2)
const countAtom = atom(0)
const resultAtom = atom<number | null>(null)

const resolve: (() => void)[] = []
const asyncAtom = atom(async (get) => {
const count = get(countAtom)
await new Promise<void>((r: { (): void; count?: number }) => {
r.count = count
resolve.push(r)
})
console.log(`resolved (${count})`)
return count
})

const derivedAtom = atom(
async (get, { setSelf }) => {
const count = get(countAtom)
await Promise.resolve()
console.log(`derived (${count})`)
const resultCount = await get(asyncAtom)
console.log(`derived (${count})`, resultCount)
setSelf(resultAtom, resultCount)
dmaskasky marked this conversation as resolved.
Show resolved Hide resolved
},
(_get, set, ...args: Parameters<Setter>) => set(...args)
)

const derivedSyncAtom = atom((get) => {
get(derivedAtom)
})

function useTest() {
useAtom(derivedSyncAtom)
useAtom(countAtom)
}
function TestComponent() {
useTest()
return null
}
const store = createStore()

const Wrapper = ({ children }: React.PropsWithChildren) => (
<Provider store={store}>{children}</Provider>
)
render(<TestComponent />, { wrapper: Wrapper })

const setCount = (arg: SetStateAction<number>) => store.set(countAtom, arg)

await waitFor(() => assert(resolve.length === 1))

resolve[0]!()

await act(() => setCount(increment))
await act(() => setCount(increment))

resolve[1]!()
resolve[2]!()

await waitFor(() => assert(store.get(countAtom) === 2))
expect(store.get(resultAtom)).toBe(2)

await act(() => setCount(increment))
await act(() => setCount(increment))

resolve[3]!()
resolve[4]!()

await waitFor(() => assert(store.get(countAtom) === 4))
expect(store.get(resultAtom)).toBe(4) // 3
})

it('[unit] resolves dependencies reliably after a delay', async () => {
dmaskasky marked this conversation as resolved.
Show resolved Hide resolved
const countAtom = atom(0)
const resultAtom = atom<number | null>(null)

const resolve: (() => void)[] = []
const asyncAtom = atom(async (get) => {
const count = get(countAtom)
await new Promise<void>((r: { (): void; count?: number }) => {
r.count = count
resolve.push(r)
})
console.log(`resolved (${count})`)
return count
})

const derivedAtom = atom(
async (get, { setSelf }) => {
const count = get(countAtom)
await Promise.resolve()
console.log(`derived (${count})`)
const asyncCount = await get(asyncAtom)
console.log(`derived (${count})`, asyncCount)
setSelf(resultAtom, asyncCount)
},
(_get, set, ...args: Parameters<Setter>) => set(...args)
)

const store = createStore()
store.sub(derivedAtom, () => {})

await waitFor(() => assert(resolve.length === 1))

resolve[0]!()

store.set(countAtom, increment)
store.set(countAtom, increment)

await waitFor(() => assert(resolve.length === 3))

resolve[1]!()
resolve[2]!()

await waitFor(() => assert(store.get(countAtom) === 2))
expect(store.get(resultAtom)).toBe(2)

store.set(countAtom, increment)
store.set(countAtom, increment)

await waitFor(() => assert(resolve.length === 5))

resolve[3]!()
resolve[4]!()

await waitFor(() => assert(store.get(countAtom) === 4))
expect(store.get(resultAtom)).toBe(4) // 3
})

function assert(condition: boolean): asserts condition {
if (!condition) {
throw new Error('assertion failed')
}
}

function increment(c: number) {
return c + 1
}
Loading