T
TanStack3y ago
stormy-gold

Passing parameters to refetch without specifying it in the querykey

I have a situation where I want to pass a parameter to refetch, but not specify it as a queryKey. The parameter is a complex object that cannot directly be used as a queryKey for various reasons. One of them being that this parameter can have different contents, yet actually be the same value. So I have a function that generates a queryKey for the parameter. So I would like to call refetch, pass the computed queryKey and the actual parameter itself. But how can I do that? I don't want the actual parameter to become part of the queryKey
3 Replies
stormy-gold
stormy-goldOP3y ago
so I want to do something like this in pseudocode refetch({ queryKey: getComputedQueryKey(parameter), actualParameter: parameter })
rival-black
rival-black3y ago
I don't think that's possible, the idea behind refetch is to refetch with the same key/parameters as far as I know. Can you show some code to help understand more about your use case?
quickest-silver
quickest-silver3y ago
refetch({ queryKey: getComputedQueryKey(parameter) > I assume you are using the query client. Its refetch function is only for refetching data for a useQuery within a component ( that matches the provided key). It shouldn't be possible to change a query key with it. Instead you should be updating the queryKey & queryFn passed to the useQuery hook. Data will be automatically fetched.
function useGetSomething(params){
return useQuery({
queryKey: computedQueryKey(params),
queryFn: () => fetchSomething(params),
});
}

function Component(){
...
const [requestParams, setParams] = useState({ v:"initially derived from props & other state" });
const queryResult = useGetSomething(requestParams);

// call setParams & update the request params, data will be refetched.
}
function useGetSomething(params){
return useQuery({
queryKey: computedQueryKey(params),
queryFn: () => fetchSomething(params),
});
}

function Component(){
...
const [requestParams, setParams] = useState({ v:"initially derived from props & other state" });
const queryResult = useGetSomething(requestParams);

// call setParams & update the request params, data will be refetched.
}
If the computedKey hasn't changed, but you still need to fetch the data with updated parameters ( in cases where you wan't to keep the previous data & keep isLoading:false ), I'd suggest handling it by slightly changing queryKey & changing keepPreviousData as needed.

Did you find this page helpful?