Skip to content

feat(query-db-collection): support automatic refetch on query invalidation #381

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

Closed
wants to merge 1 commit into from
Closed
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
19 changes: 18 additions & 1 deletion packages/query-db-collection/src/query.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { QueryObserver } from "@tanstack/query-core"
import { QueryObserver, partialMatchKey } from "@tanstack/query-core"
import {
GetKeyRequiredError,
QueryClientRequiredError,
Expand Down Expand Up @@ -488,8 +488,25 @@ export function queryCollectionOptions<
}
})

const invalidationUnsubscribe = queryClient
.getQueryCache()
.subscribe((event) => {
const { type, action, query } = event

if (
type !== `updated` ||
action.type !== `invalidate` ||
!partialMatchKey(queryKey, query.queryKey)
) {
return
}

refetch()
})

return async () => {
actualUnsubscribeFn()
invalidationUnsubscribe()
await queryClient.cancelQueries({ queryKey })
queryClient.removeQueries({ queryKey })
}
Expand Down
34 changes: 33 additions & 1 deletion packages/query-db-collection/tests/query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -834,7 +834,7 @@ describe(`QueryCollection`, () => {

// Wait for refetch to complete
await vi.waitFor(() => {
expect(queryFn).toHaveBeenCalledTimes(2)
expect(queryFn).toHaveBeenCalledTimes(3)
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test might need to be changed, open to feedback!

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

huh wait... did we already have support for invalidating queries?? 😅 It looks like we just added another implementation... it seems Query was already handling this internally... if this is the case, then we have a lot less to do, just update the docs/jsdocs a bit.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Definitely appears so, and to be honest, that's what I've been confused about. Still not completely following the need for refetch in general, if under the hood we're reading from the cache from query? But I don't have full context as well. 😄

I'll go ahead and remove the changes.

If this behavior is handled by Query already, do we want to mention that directly in docs/query-collection.md? What did you have in mind?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah when building this originally and writing this issue it didn't occur to me that the query client would just keep calling the queryFn like normal.

Refetch is nice as not everyone is migrating from a full blown normal Query setup so they might just have a one-off collection that they want to be able to manually refetch. It depends I suppose on your mental model of your state. A web of data or standalone table-like collections.

There's a few places where we mention calling other collections to refetch (search for "refetch". So we should mention first that you can invalidate a tag or just directly tell those collections to refetch.

expect(collection.size).toBe(2)
})

Expand Down Expand Up @@ -1603,4 +1603,36 @@ describe(`QueryCollection`, () => {
expect(collection.size).toBe(0)
expect(collection.status).toBe(`ready`)
})

it(`should not refetch after cleanup unsubscribes from cache`, async () => {
const queryKey = [`todos`, 123]
const queryFn = vi.fn().mockResolvedValue([{ id: `1`, name: `Initial` }])

const config: QueryCollectionConfig<TestItem> = {
id: `unsubscribe-test`,
queryClient,
queryKey,
queryFn,
getKey,
startSync: true,
}

const collection = createCollection(queryCollectionOptions(config))

await vi.waitFor(() => {
expect(queryFn).toHaveBeenCalledTimes(1)
})

await collection.cleanup() // Should unsubscribe from QueryCache

// Update data
queryFn.mockResolvedValue([{ id: `1`, name: `Updated` }])

// This should NOT trigger another fetch
await queryClient.invalidateQueries({ queryKey: [`todos`] })

await new Promise((r) => setTimeout(r, 100)) // Give event loop time

expect(queryFn).toHaveBeenCalledTimes(1)
})
})
Loading