Skip to content

Commit

Permalink
fix(core): make sure queries that never fetched can be garbage collec…
Browse files Browse the repository at this point in the history
…ted (#4898)

* fix(core): make sure queries that never fetched can ge garbage collected

This is important if data comes into the cache via a non-fetching method (like setQueryData or hydration) AND there is no active observer for them. Without this, they would never be gc'ed, but they should be after the default cacheTime

* tests: simplify svelte test
  • Loading branch information
TkDodo committed Jan 30, 2023
1 parent 2861488 commit 1615509
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 10 deletions.
1 change: 1 addition & 0 deletions packages/query-core/src/query.ts
Expand Up @@ -173,6 +173,7 @@ export class Query<
this.queryHash = config.queryHash
this.initialState = config.state || getDefaultState(this.options)
this.state = this.initialState
this.scheduleGc()
}

get meta(): QueryMeta | undefined {
Expand Down
24 changes: 24 additions & 0 deletions packages/query-core/src/tests/query.test.tsx
Expand Up @@ -883,4 +883,28 @@ describe('query', () => {

expect(initialDataUpdatedAtSpy).toHaveBeenCalled()
})

test('queries should be garbage collected even if they never fetched', async () => {
const key = queryKey()

queryClient.setQueryDefaults(key, { cacheTime: 10 })

const fn = jest.fn()

const unsubscribe = queryClient.getQueryCache().subscribe(fn)

queryClient.setQueryData(key, 'data')

await waitFor(() =>
expect(fn).toHaveBeenCalledWith(
expect.objectContaining({
type: 'removed',
}),
),
)

expect(queryClient.getQueryCache().findAll()).toHaveLength(0)

unsubscribe()
})
})
18 changes: 8 additions & 10 deletions packages/svelte-query/src/__tests__/createQuery.test.ts
@@ -1,11 +1,11 @@
import { describe, it, expect } from 'vitest'
import { render, screen } from '@testing-library/svelte'
import { render, waitFor } from '@testing-library/svelte'
import CreateQuery from './CreateQuery.svelte'
import { sleep } from './utils'

describe('createQuery', () => {
it('Render and wait for success', async () => {
render(CreateQuery, {
const rendered = render(CreateQuery, {
props: {
options: {
queryKey: ['test'],
Expand All @@ -17,14 +17,12 @@ describe('createQuery', () => {
},
})

expect(screen.queryByText('Loading')).toBeInTheDocument()
expect(screen.queryByText('Error')).not.toBeInTheDocument()
expect(screen.queryByText('Success')).not.toBeInTheDocument()

await sleep(20)
await waitFor(() => {
expect(rendered.getByText('Loading')).toBeInTheDocument()
})

expect(screen.queryByText('Success')).toBeInTheDocument()
expect(screen.queryByText('Loading')).not.toBeInTheDocument()
expect(screen.queryByText('Error')).not.toBeInTheDocument()
await waitFor(() => {
expect(rendered.getByText('Success')).toBeInTheDocument()
})
})
})

0 comments on commit 1615509

Please sign in to comment.