#useQueries with already created hooks?

11 messages · Page 1 of 1 (latest)

simple mortar
#

I created some hooks to use in my components:

export function useSaStates() {
    return useQuery(keys.saStates.queryKey, fetchSaStates, {});
}
export function useLaStates() {
    return useQuery(keys.laStates.queryKey, fetchLaStates, {});
}

Can I use useQueries with these already created hooks, or do I need to define them in the useQueries itself?

Any insight would be helpful, thank you!

arctic portal
#

Hi you can extract the query configurations (queryKey, queryFn, options) and use these factorised options in all your hooks

simple mortar
#

Hi @arctic portal , thanks for replying 😄

What do you mean by extracting, can this be done directly from a custom hook?

Like this:

const {queryKey, queryFn, options} = useSaStates() 

Or do you mean before even defining the custom hooks?

arctic portal
#

You could have an external file in which you define your different queries (key, function etc.). Export the configs and use them in your custom hooks

#

Or you could use queryClient defaults options

simple mortar
#

Gotcha, ill read all of these

#

Thank you very much 😄

#

spare cobalt
#

yeah my recommendation would be to basically take the query key factory one step further into just query factories:

const saStatesQuery = {
  queryKey: [...],
  queryFn: fetchSaStates
}

const laStatesQuery = {
  queryKey: [...],
  queryFn: fetchLaStates
}

export function useSaStates() {
    return useQuery(saStatesQuery);
}
export function useLaStates() {
    return useQuery(laStatesQuery);
}

export function useBoth() {
  return useQueries({ queries: [saStatesQuery, laStatesQuery] })
}

the beauty here is that both useQuery and useQueries accept an object 🙂