Is there a way to convert query data and mapping based on types in react-query v4?
P粉238355860
P粉238355860 2024-01-08 23:03:24
0
1
563

I'm trying to transform query data from an API response. More specifically, I want to add two additional properties. That's why I'm using the select configuration in the useQuery hook like this: But in this case I don't get the suggestion for the extra two properties. That's why I added another model and used it with useQuery hook like this: But it gets error.

I'm stuck on this problem.

Edit on codesandbox

P粉238355860
P粉238355860

reply all(1)
P粉262113569

Try this, the problem is that the first generic type parameter of useQuery is not the returned data type. It is the queryFn return type. You can put ModifiedProduct[] in the third generic type parameter or somewhere the code infers 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;
    }
  });
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!