T
TanStack3y ago
national-gold

Using keepPreviousData and remove

How should I be using keepPreviousData: true and remove() together? We have a form for user defined search criteria that only searches on button click and also includes a clear button which clears both the form and our grid of results. I followed the example here https://tanstack.com/query/latest/docs/react/guides/disabling-queries and it's mostly working how I want, but because the input values are part of my queryKey the data in the cache is lost as the user types. So I added keepPreviousData: true which then fixes that, but now my clear button doesn't clear the cache. What am I foolishly overlooking?
const { reset, watch } = methods
const values = watch()

const {
data,
status,
remove: clear,
refetch: search
} = useQuery({
enabled: false,
keepPreviousData: true,
queryKey: ['foobar', { ...values }],
queryFn: ({ signal }) => foobar.query({ ...values }, signal)
})

return (
...
<Button
text='Clear Search'
onClick={(): void => {
clear()
reset()
}}
/>
<Button
onClick={search}
text='Search'
/>
...
)
const { reset, watch } = methods
const values = watch()

const {
data,
status,
remove: clear,
refetch: search
} = useQuery({
enabled: false,
keepPreviousData: true,
queryKey: ['foobar', { ...values }],
queryFn: ({ signal }) => foobar.query({ ...values }, signal)
})

return (
...
<Button
text='Clear Search'
onClick={(): void => {
clear()
reset()
}}
/>
<Button
onClick={search}
text='Search'
/>
...
)
2 Replies
flat-fuchsia
flat-fuchsia3y ago
Disabling/Pausing Queries | TanStack Query Docs
If you ever want to disable a query from automatically running, you can use the enabled = false option. When enabled is false:
national-gold
national-goldOP3y ago
Yeah I did read and try to follow that. I think my problem is just a bad choice on my part to use watch and it causing extra renders. I should probably use a state variable that I set on search click and have something like:
useQuery({
enabled: Boolean(params),
queryKey: ['foobar', { ...params }],
queryFn: ({ signal }) => foobar.query({ ...params }, signal)
})
useQuery({
enabled: Boolean(params),
queryKey: ['foobar', { ...params }],
queryFn: ({ signal }) => foobar.query({ ...params }, signal)
})
On my "Search" button I have:
onClick{(): void => {
setParams(getValues())
}}
onClick{(): void => {
setParams(getValues())
}}
However that means if I click "Search" again without changing values there is no refetch. Is it okay to change it to:
onClick{(): Promise<void> => {
setParams(getValues())
await refetch()
}}
onClick{(): Promise<void> => {
setParams(getValues())
await refetch()
}}
Or do I need to add some logic to not call refetch when getValues() actually affects my queryKey? Or should I just do { cancelRefetch: false }?

Did you find this page helpful?