Using a selection / projection of a query #6597
-
I have a type ProductName = string;
type Price = number;
type PriceList = Record<ProductName, Price>;
const usePrices: () => UseQueryResult<PriceList> = () => {
return useQuery({
queryKey: ['prices'],
queryFn: () => fetch('/api/prices'),
})
} I want to build another hook that transforms the result of the first query. One way to do this would be to return the transformation directly: const usePrice: (name: ProductName) => Price = () => {
const prices = usePrices()
return prices.data?.[name] ?? 0
} The downside here is that I lose all the metadata like whether the query is loading. I could instead use a dependent query: const usePrice: (name: ProductName) => UseQueryResult<Price> = () => {
const prices = usePrices()
return useQuery({
queryKey: ['prices', name],
queryFn: () => prices.data?.[name] ?? 0,
enabled: !!prices.data
})
} The problem with this one is that My last idea was to destructure the result and merge in my custom data: const usePrice: (name: ProductName) => UseQueryResult<Price> = () => {
const prices = usePrices()
return {
...prices,
data: prices.data?.[name] ?? 0,
}
} But the types are wrong. Among other things, Possibly related: #4727 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
this can be done with select:
|
Beta Was this translation helpful? Give feedback.
this can be done with select: