search

Home  >  Q&A  >  body text

Is there a way to convert query data and mapping based on types in react-query v4?

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粉238355860P粉238355860326 days ago627

reply all(1)I'll reply

  • P粉262113569

    P粉2621135692024-01-09 18:12:49

    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;
        }
      });

    reply
    0
  • Cancelreply