Skip to content

fix(queryObserver): Load currentResult for placeholder data after first update #1717

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
10 changes: 9 additions & 1 deletion src/core/queryObserver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -406,10 +406,18 @@ export class QueryObserver<
typeof data === 'undefined' &&
status === 'loading'
) {
const placeholderData =
let placeholderData : TData | undefined;

// Use the previous result data if exists instead of readding placeholder data
if(this.currentResult && typeof this.currentResult.data !== 'undefined') {
placeholderData = this.currentResult.data
} else {
placeholderData =
typeof this.options.placeholderData === 'function'
? (this.options.placeholderData as PlaceholderDataFunction<TData>)()
: this.options.placeholderData
}

if (typeof placeholderData !== 'undefined') {
status = 'success'
data = placeholderData
Expand Down
25 changes: 25 additions & 0 deletions src/core/tests/queryObserver.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -329,4 +329,29 @@ describe('queryObserver', () => {
expect(results[0].data).toBe('data')
unsubscribe()
})

test('should only call placeholder data once for relevant data', async () => {
const key = queryKey()
const placeholderData = jest.fn(() => 'placeholder');
const observer = new QueryObserver(queryClient, {
queryKey: key,
queryFn: () => 'data',
placeholderData,
})

expect(observer.getCurrentResult()).toMatchObject({
status: 'success',
data: 'placeholder',
})

const results: QueryObserverResult<unknown>[] = []

const unsubscribe = observer.subscribe(x => {
results.push(x)
})

await sleep(10)
expect(placeholderData).toBeCalledTimes(1)
unsubscribe()
})
})