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 8 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
37 changes: 37 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,41 @@ 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)

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

this.setData(data)
try {
this.setData(data)
} catch (error) {
onError(error as TError)
return
}

// Notify cache callback
this.#cache.config.onSuccess?.(data, this as Query<any, any, any, any>)
Expand Down
9 changes: 9 additions & 0 deletions packages/query-core/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -246,6 +246,15 @@ export function replaceEqualDeep(a: any, b: any): any {
return a
}

if (process.env.NODE_ENV !== 'production') {
try {
JSON.stringify(a)
JSON.stringify(b)
} catch {
throw new Error('Values are not serializable')
TkDodo marked this conversation as resolved.
Show resolved Hide resolved
}
}

const array = isPlainArray(a) && isPlainArray(b)

if (array || (isPlainObject(a) && isPlainObject(b))) {
Expand Down
Loading