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(query-core): handle errors that occur inside setData method #7966

Merged
merged 12 commits into from
Aug 30, 2024
Merged
Show file tree
Hide file tree
Changes from 3 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
40 changes: 40 additions & 0 deletions packages/query-core/src/__tests__/query.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -965,4 +965,44 @@ describe('query', () => {
await sleep(60) // let it resolve
expect(spy).toHaveBeenCalledWith('1 - 2')
})

it('should have an error status when queryFn data is not serializable', async () => {
const key = queryKey()

const queryFn = vi.fn()

queryFn.mockImplementation(async () => {
await sleep(10)

const data: Array<{
id: number
name: string
link: null | { id: number; name: string; link: unknown }
}> = Array.from({ length: 5 })
.fill(null)
.map((_, index) => ({
id: index,
name: `name-${index}`,
link: null,
}))

if (data[0] && data[1]) {
data[0].link = data[1]
data[1].link = data[0]
}

return data
})

await queryClient.prefetchQuery({ queryKey: key, queryFn })

const query = queryCache.find({ queryKey: key })!

expect(queryFn).toHaveBeenCalledTimes(1)

// NOTE: need second query fetch, cause for first fetch 'prevData' for structural sharing is 'undefined'
await query.fetch()
TkDodo marked this conversation as resolved.
Show resolved Hide resolved

expect(query.state.status).toBe('error')
})
})
6 changes: 5 additions & 1 deletion packages/query-core/src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -499,7 +499,11 @@ export class Query<
return
}

this.setData(data)
try {
this.setData(data)
} catch (error) {
onError(error as TError)
}
TkDodo marked this conversation as resolved.
Show resolved Hide resolved

// Notify cache callback
this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
Expand Down
Loading