Skip to content

Commit 6b849cf

Browse files
mooxlampagentTkDodo
authored
fix(query-core): keep a placeholder that select maps to undefined (#12575)
Amp-Thread-ID: https://ampcode.com/threads/T-01a1c72d-7954-7320-aa9d-9f2611a997c4 Co-authored-by: Amp <amp@ampcode.com> Co-authored-by: Dominik Dorfmeister 🔮 <office@dorfmeister.cc>
1 parent 8b2e8af commit 6b849cf

4 files changed

Lines changed: 110 additions & 3 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@tanstack/query-core': patch
3+
---
4+
5+
Keep a memoized placeholder result when `select` maps it to `undefined`, so a query with `keepPreviousData` that is disabled or still loading no longer loops between `pending` and `success`.

‎packages/query-core/src/__tests__/queryObserver.test.tsx‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
QueryClient,
55
QueryObserver,
66
focusManager,
7+
keepPreviousData,
78
noop,
89
timeoutManager,
910
} from '..'
@@ -2000,4 +2001,44 @@ describe('queryObserver', () => {
20002001
unsubscribe2()
20012002
})
20022003
})
2004+
2005+
it('should keep a placeholder that select maps to undefined', async () => {
2006+
const key = createKey()
2007+
const options = (id: string) =>
2008+
queryClient.defaultQueryOptions({
2009+
queryKey: [...key, id],
2010+
queryFn: () => [id],
2011+
enabled: id !== '',
2012+
placeholderData: keepPreviousData,
2013+
select: (items: Array<string>) => items.find((item) => item === id),
2014+
})
2015+
const observer = new QueryObserver(queryClient, options('a'))
2016+
const unsubscribe = observer.subscribe(() => undefined)
2017+
await vi.advanceTimersByTimeAsync(0)
2018+
2019+
// 'b' is still loading, '' is disabled. What useQuery does on every
2020+
// render: an optimistic result, then the options
2021+
for (const id of ['b', '']) {
2022+
for (let i = 0; i < 2; i++) {
2023+
expect(observer.getOptimisticResult(options(id)).status).toBe('success')
2024+
observer.setOptions(options(id))
2025+
expect(observer.getCurrentResult()).toMatchObject({
2026+
status: 'success',
2027+
isPlaceholderData: true,
2028+
data: undefined,
2029+
})
2030+
}
2031+
await vi.advanceTimersByTimeAsync(0)
2032+
}
2033+
2034+
// A new placeholderData is not memoized, so its undefined means pending
2035+
observer.setOptions({ ...options(''), placeholderData: () => undefined })
2036+
expect(observer.getCurrentResult()).toMatchObject({
2037+
status: 'pending',
2038+
isPlaceholderData: false,
2039+
data: undefined,
2040+
})
2041+
2042+
unsubscribe()
2043+
})
20032044
})

‎packages/query-core/src/queryObserver.ts‎

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -648,10 +648,10 @@ export class QueryObserver<
648648
let placeholderData
649649

650650
// Memoize placeholder data
651-
if (
651+
const isMemoizedPlaceholder =
652652
prevResult?.isPlaceholderData &&
653653
options.placeholderData === prevResultOptions?.placeholderData
654-
) {
654+
if (isMemoizedPlaceholder) {
655655
placeholderData = prevResult.data
656656
// we have to skip select when reading this memoization
657657
// because prevResult.data is already "selected"
@@ -669,7 +669,8 @@ export class QueryObserver<
669669
: options.placeholderData
670670
}
671671

672-
if (placeholderData !== undefined) {
672+
// A memoized placeholder stays one even when `select` turned it into undefined
673+
if (isMemoizedPlaceholder || placeholderData !== undefined) {
673674
status = 'success'
674675
data = replaceData(
675676
prevResult?.data,

‎packages/react-query/src/__tests__/useQuery.test.tsx‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7130,4 +7130,64 @@ describe('useQuery', () => {
71307130

71317131
expect(queryFn.mock.calls).toStrictEqual([['a'], ['b']])
71327132
})
7133+
7134+
it('should not loop when a query with select and keepPreviousData is disabled', async () => {
7135+
const key = createKey()
7136+
7137+
function Page() {
7138+
const [id, setId] = React.useState('a')
7139+
const { data } = useQuery({
7140+
queryKey: [...key, id],
7141+
queryFn: () => [id],
7142+
enabled: id !== '',
7143+
placeholderData: keepPreviousData,
7144+
select: (items) => items.find((item) => item === id),
7145+
})
7146+
7147+
return (
7148+
<button onClick={() => setId('')}>{`picked: ${data ?? 'none'}`}</button>
7149+
)
7150+
}
7151+
7152+
const rendered = renderWithClient(queryClient, <Page />)
7153+
await vi.advanceTimersByTimeAsync(0)
7154+
expect(rendered.getByText('picked: a')).toBeInTheDocument()
7155+
7156+
fireEvent.click(rendered.getByRole('button'))
7157+
await vi.advanceTimersByTimeAsync(0)
7158+
expect(rendered.getByText('picked: none')).toBeInTheDocument()
7159+
})
7160+
7161+
it('should settle as placeholder data when select maps keepPreviousData to undefined', async () => {
7162+
const key = createKey()
7163+
const states: Array<UseQueryResult<string | undefined>> = []
7164+
7165+
function Page() {
7166+
const [id, setId] = React.useState('a')
7167+
const state = useQuery({
7168+
queryKey: [...key, id],
7169+
queryFn: () => [id],
7170+
enabled: id !== '',
7171+
placeholderData: keepPreviousData,
7172+
select: (items) => items.find((item) => item === id),
7173+
})
7174+
states.push(state)
7175+
7176+
return (
7177+
<button onClick={() => setId('')}>{`status: ${state.status}`}</button>
7178+
)
7179+
}
7180+
7181+
const rendered = renderWithClient(queryClient, <Page />)
7182+
await vi.advanceTimersByTimeAsync(0)
7183+
expect(rendered.getByText('status: success')).toBeInTheDocument()
7184+
7185+
fireEvent.click(rendered.getByRole('button'))
7186+
await vi.advanceTimersByTimeAsync(0)
7187+
expect(states.at(-1)).toMatchObject({
7188+
status: 'success',
7189+
isPlaceholderData: true,
7190+
data: undefined,
7191+
})
7192+
})
71337193
})

0 commit comments

Comments
 (0)