Skip to content

Commit

Permalink
fix: make sure queries with only inactive observers are also invalida…
Browse files Browse the repository at this point in the history
…ted (#949)
  • Loading branch information
boschni committed Sep 1, 2020
1 parent e12d002 commit 52607f6
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 10 deletions.
6 changes: 5 additions & 1 deletion src/core/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,11 @@ export class Query<TResult, TError> {

private dispatch(action: Action<TResult, TError>): void {
this.state = queryReducer(this.state, action)
this.observers.forEach(d => d.onQueryUpdate(this.state, action))

this.observers.forEach(observer => {
observer.onQueryUpdate(this.state, action)
})

this.notifyGlobalListeners(this)
}

Expand Down
16 changes: 7 additions & 9 deletions src/core/queryCache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,9 @@ export class QueryCache {
0
)

this.globalListeners.forEach(d => d(this, query))
this.globalListeners.forEach(listener => {
listener(this, query)
})
}

getDefaultConfig() {
Expand Down Expand Up @@ -193,14 +195,10 @@ export class QueryCache {
try {
await Promise.all(
this.getQueries(predicate, options).map(query => {
if (query.observers.length) {
if (refetchActive && query.isEnabled()) {
return query.fetch()
}
} else {
if (refetchInactive) {
return query.fetch()
}
const enabled = query.isEnabled()

if ((enabled && refetchActive) || (!enabled && refetchInactive)) {
return query.fetch()
}

return undefined
Expand Down
50 changes: 50 additions & 0 deletions src/react/tests/useQuery.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,56 @@ describe('useQuery', () => {
return null
})

it.only('should update disabled query when updated with invalidateQueries', async () => {
const key = queryKey()
const states: QueryResult<number>[] = []
let count = 0

function Page() {
const state = useQuery(
key,
async () => {
await sleep(10)
count++
return count
},
{ enabled: false }
)

states.push(state)

React.useEffect(() => {
setTimeout(() => {
queryCache.invalidateQueries(key, { refetchInactive: true })
}, 20)
}, [])

return null
}

render(<Page />)

await waitFor(() => expect(states.length).toBe(3))

expect(states).toMatchObject([
{
data: undefined,
isFetching: false,
isSuccess: false,
},
{
data: undefined,
isFetching: true,
isSuccess: false,
},
{
data: 1,
isFetching: false,
isSuccess: true,
},
])
})

it('should keep the previous data when keepPreviousData is set', async () => {
const key = queryKey()
const states: QueryResult<number>[] = []
Expand Down

1 comment on commit 52607f6

@vercel
Copy link

@vercel vercel bot commented on 52607f6 Sep 1, 2020

Choose a reason for hiding this comment

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

Please sign in to comment.