I have a useQuery fetching some data that is by default cached on the server. But sometimes, when a button is clicked, I want to send an additional parameter (force=true) that will force the server to refresh the data for that same query. I'm not able to do that properly:
const {data, refetch} = useQuery(['myQuery', id], () => goFetch({id}).then(response => response.data))
Ideally, that would be something like this:
const handleClick = () => {
refetch({force: true})
}
but that doesn't work.
One workaround is having a useState like this:
const [force, setForce] = useState(false)
const {data} = useQuery(['myQuery', id, force], () => goFetch({id, force}).then(response => response.data))
const handleClick = () => {
setForce(true)
}
Kinda works, but then I have to set the force parameter back to false, and it's going to be refetched again when it changes. Is there a more elegant solution that you would recommend?
I assume you don't actually need force and are using that to "trick" react query into thinking it needs to refetch.
In that case invalidate the query instead, this removes the query cache forcing the query to be called again.
ref: https://react-query-v3.tanstack.com/guides/query-invalidation
example: https://codesandbox.io/s/wild-wave-k93512?file=/src/App.tsx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With