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(react): ensure edges are materialized when React runs effects #166

Merged
merged 1 commit into from
Feb 7, 2025
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
9 changes: 6 additions & 3 deletions packages/react/src/hooks/useAtomInstance.ts
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ export const useAtomInstance: {

let edge: DependentEdge | undefined

const addEdge = () => {
const addEdge = (isMaterialized?: boolean) => {
if (!ecosystem._graph.nodes[instance.id]?.dependents.get(dependentKey)) {
edge = ecosystem._graph.addEdge(
dependentKey,
Expand All @@ -94,6 +94,7 @@ export const useAtomInstance: {
)

if (edge) {
edge.isMaterialized = isMaterialized
edge.dependentKey = dependentKey

if (instance._lastEdge) {
Expand Down Expand Up @@ -131,8 +132,10 @@ export const useAtomInstance: {
}

// Try adding the edge again (will be a no-op unless React's StrictMode ran
// this effect's cleanup unnecessarily)
addEdge()
// this effect's cleanup unnecessarily OR other effects in child components
// cleaned up this component's edges before it could materialize them.
// That's fine, just recreate them with `isMaterialized: true` now)
addEdge(true)

// use the referentially stable render function as a ref :O
;(render as any).mounted = true
Expand Down
9 changes: 6 additions & 3 deletions packages/react/src/hooks/useAtomSelector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,13 +78,14 @@ export const useAtomSelector = <T, Args extends any[]>(

let edge: DependentEdge | undefined

const addEdge = () => {
const addEdge = (isMaterialized?: boolean) => {
if (!_graph.nodes[cache.id]?.dependents.get(dependentKey)) {
edge = _graph.addEdge(dependentKey, cache.id, OPERATION, External, () => {
if ((render as any).mounted) render({})
})

if (edge) {
edge.isMaterialized = isMaterialized
edge.dependentKey = dependentKey

if (cache._lastEdge) {
Expand Down Expand Up @@ -143,8 +144,10 @@ export const useAtomSelector = <T, Args extends any[]>(
}

// Try adding the edge again (will be a no-op unless React's StrictMode ran
// this effect's cleanup unnecessarily)
addEdge()
// this effect's cleanup unnecessarily OR other effects in child components
// cleaned up this component's edges before it could materialize them.
// That's fine, just recreate them with `isMaterialized: true` now)
addEdge(true)

// use the referentially stable render function as a ref :O
;(render as any).mounted = true
Expand Down
171 changes: 171 additions & 0 deletions packages/react/test/regressions/165.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
import {
atom,
AtomGetters,
useAtomSelector,
useAtomState,
useAtomValue,
} from '@zedux/react'
import React from 'react'
import { renderInEcosystem } from '../utils/renderInEcosystem'
import { act } from '@testing-library/react'
import { ecosystem } from '../utils/ecosystem'

const itemsAtom = atom('items', [{ id: 1 }])
const exampleAtom = atom('example', 'a')
const selector = ({ get }: AtomGetters) => get(exampleAtom)

let isUsingSelectors = false

function Item({ id }: { id: number }) {
const exampleValue = isUsingSelectors
? useAtomSelector(selector)
: useAtomValue(exampleAtom)

return <div data-testid={`item${id}`}>{exampleValue}</div>
}

function List() {
const [items, setItems] = useAtomState(itemsAtom)
const exampleValue = isUsingSelectors
? useAtomSelector(selector)
: useAtomValue(exampleAtom)

return (
<div>
<div data-testid="list">{exampleValue}</div>
<ul>
{items.map(item => (
<Item key={item.id} id={item.id} />
))}
</ul>
<button
data-testid="addItem"
onClick={() => setItems(items => [...items, { id: items.length + 1 }])}
>
Add Item
</button>
</div>
)
}

describe('issue #165', () => {
test('atoms in strict mode', async () => {
;(globalThis as any).useReact18UseId()
isUsingSelectors = false

const { findByTestId } = renderInEcosystem(<List />, {
useStrictMode: true,
})
const button = await findByTestId('addItem')
const list = await findByTestId('list')
const item1 = await findByTestId('item1')

expect(list).toHaveTextContent('a')
expect(item1).toHaveTextContent('a')

act(() => {
button.click()
})

const item2 = await findByTestId('item2')

expect(item2).toHaveTextContent('a')

act(() => {
ecosystem.getInstance(exampleAtom).setState('aa')
})

expect(list).toHaveTextContent('aa')
expect(item1).toHaveTextContent('aa')
expect(item2).toHaveTextContent('aa')
})

test('atoms without strict mode', async () => {
;(globalThis as any).useReact18UseId()
isUsingSelectors = false

const { findByTestId } = renderInEcosystem(<List />)
const button = await findByTestId('addItem')
const list = await findByTestId('list')
const item1 = await findByTestId('item1')

expect(list).toHaveTextContent('a')
expect(item1).toHaveTextContent('a')

act(() => {
button.click()
})

const item2 = await findByTestId('item2')

expect(item2).toHaveTextContent('a')

act(() => {
ecosystem.getInstance(exampleAtom).setState('aa')
})

expect(list).toHaveTextContent('aa')
expect(item1).toHaveTextContent('aa')
expect(item2).toHaveTextContent('aa')
})

test('selectors in strict mode', async () => {
;(globalThis as any).useReact18UseId()
isUsingSelectors = true

const { findByTestId } = renderInEcosystem(<List />, {
useStrictMode: true,
})
const button = await findByTestId('addItem')
const list = await findByTestId('list')
const item1 = await findByTestId('item1')

expect(list).toHaveTextContent('a')
expect(item1).toHaveTextContent('a')

act(() => {
button.click()
})

const item2 = await findByTestId('item2')

expect(item2).toHaveTextContent('a')

act(() => {
ecosystem.getInstance(exampleAtom).setState('aa')
})

expect(list).toHaveTextContent('aa')
expect(item1).toHaveTextContent('aa')
expect(item2).toHaveTextContent('aa')
})

test('selectors without strict mode', async () => {
;(globalThis as any).useReact18UseId()
isUsingSelectors = true

const { findByTestId } = renderInEcosystem(<List />)
const button = await findByTestId('addItem')
const list = await findByTestId('list')
const item1 = await findByTestId('item1')

expect(list).toHaveTextContent('a')
expect(item1).toHaveTextContent('a')

act(() => {
button.click()
})

const item2 = await findByTestId('item2')

expect(item2).toHaveTextContent('a')

act(() => {
ecosystem.getInstance(exampleAtom).setState('aa')
})

expect(list).toHaveTextContent('aa')
expect(item1).toHaveTextContent('aa')
expect(item2).toHaveTextContent('aa')
})
})
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ exports[`useAtomSelector inline selector that returns a different object referen
"createdAt": 123456789,
"dependentKey": "Test-:rb:",
"flags": 2,
"isMaterialized": undefined,
"operation": "useAtomSelector",
},
},
Expand Down Expand Up @@ -137,6 +138,7 @@ exports[`useAtomSelector inline selector that returns a different object referen
"createdAt": 123456789,
"dependentKey": "Test-:rb:",
"flags": 2,
"isMaterialized": undefined,
"operation": "useAtomSelector",
"task": undefined,
},
Expand Down