TanStackT
TanStack3y ago
4 replies
sad-indigo

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'
   />
  ...
)
Was this page helpful?