T
TanStack2y ago
sensitive-blue

How to refetch if queryKey is unchanged

let [foo, setFoo] = useLocalStorage('myfoo')
let [result, setResult] = useLocalStorage('myresult')

useQuery({
queryKey: [foo],
initialData: { result },
refetchOnMount: false,
enabled: Boolean(foo),
queryFn: async() => {
const res = await fetch(foo)
let result = await res.json()
setResult(result)
return { result }
}
})

function onSubmit(nextFoo: string) {
setFoo(nextFoo)
}
let [foo, setFoo] = useLocalStorage('myfoo')
let [result, setResult] = useLocalStorage('myresult')

useQuery({
queryKey: [foo],
initialData: { result },
refetchOnMount: false,
enabled: Boolean(foo),
queryFn: async() => {
const res = await fetch(foo)
let result = await res.json()
setResult(result)
return { result }
}
})

function onSubmit(nextFoo: string) {
setFoo(nextFoo)
}
hi everyone, i am trying to get the above code to work, but if the user submits the form again with the same value of "foo" i want to refetch. currently it only refetches when foo is changes between form submissions
2 Replies
sensitive-blue
sensitive-blueOP2y ago
I know that I could do something like
function onSubmit(nextFoo: string) {
if (foo === nextFoo) {
refetch()
} else {
setFoo(foo)
}
}
function onSubmit(nextFoo: string) {
if (foo === nextFoo) {
refetch()
} else {
setFoo(foo)
}
}
however the reality is that foo is a complex object, so the foo === nextFoo comparison would have to be a deep equality check and im hoping there is a different way to solve this
wise-white
wise-white2y ago
what if you introduce a version timestamp into the query key and increment it during submission
function onSubmit(nextFoo: string) {
setFoo(nextFoo);
setVersion(prev => prev + 1);
}
function onSubmit(nextFoo: string) {
setFoo(nextFoo);
setVersion(prev => prev + 1);
}
version would be another state second argument in the query key

Did you find this page helpful?