英文:
Is there any way to transform query data and map according to that type in react-query v4?
问题
I am trying to transform query data from API response. More specifically I want to add two additional properties. That is why I use select
configuration in useQuery
hook like this:
But in this case, I didn't get a suggestion for the extra two properties. That's why I've added another model and used it with the useQuery
hook like this:
But it's throwing an error.
I am stuck with this.
Edit on codesandbox
英文:
I am trying to transform query data from API response. More specifically I want to add two additional property. That is why I use select
configuration in useQuery
hook like this:
But in this case I didn't get suggestion for extra two properties. That's why I've add another model and use it with useQuery
hook like this:
But it troughing error.
I am stucked with this.
edit on codesandbox
答案1
得分: 3
The problem is that the first generic type parameter of useQuery
should not be the returned data type but the queryFn
return type. You can put ModifiedProduct[]
as the third generic type parameter or let the code infer it.
const { data, isLoading } = useQuery({
queryKey: ["fetch-products"],
queryFn: fetchProducts,
select: (data) => {
const items = data.map(
(prod): ModifiedProduct => ({
...prod,
dateOfAdd: new Date(),
dateOfUpdate: new Date()
})
);
return items;
}
});
// This should also work
const { data, isLoading } = useQuery<Product[], unknown, ModifiedProduct[]>({
queryKey: ["fetch-products"],
queryFn: fetchProducts,
select: (data) => {
const items = data.map(
(prod): ModifiedProduct => ({
...prod,
dateOfAdd: new Date(),
dateOfUpdate: new Date()
})
);
return items;
}
});
英文:
Try this, the probblem is that the first generic type parameter of useQuery
is not the returned data type. It's the queryFn
return type. You can put the ModifiedProduct[]
to the third generic type parameter or that the code infer itself.
const { data, isLoading } = useQuery({
queryKey: ["fetch-products"],
queryFn: fetchProducts,
select: (data) => {
const items = data.map(
(prod): ModifiedProduct => ({
...prod,
dateOfAdd: new Date(),
dateOfUpdate: new Date()
})
);
return items;
}
});
// this should also work
const { data, isLoading } = useQuery<Product[], unknown, ModifiedProduct[]>({
queryKey: ["fetch-products"],
queryFn: fetchProducts,
select: (data) => {
const items = data.map(
(prod): ModifiedProduct => ({
...prod,
dateOfAdd: new Date(),
dateOfUpdate: new Date()
})
);
return items;
}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论