Home > Back-end >  How pass props to external async components in typeScript and reactQuery?
How pass props to external async components in typeScript and reactQuery?

Time:06-29

I have problem with pass props to external components in next.js I have problem with line

  const { isLoading, data, error } = useQuery("products", getProducts(1));

getProducts(1)) -> How I should pass props to this component?

page:

import { useQuery } from "react-query";
import { getProducts } from "../components/task-1/getProducts-0";

export const ProductsPage = () => {
  const { isLoading, data, error } = useQuery("products", getProducts(1));

  if (isLoading) {
    return <div>Loading...</div>;
  }

  if (!data || error) {
    return <div>Error#!</div>;
  }

  return <>...</>;
};

export default ProductsPage;

component:

export const getProducts = async (id: number) => {
    const rest = await fetch(
        `https://fakestoreapi.com/products/${id}`
    );
    const data: ProductApi[] = await rest.json();
    return data;
};

interface ProductApi {
    id: number;
    title: string;
    price: number;
    description: string;
    category: string;
    image: string;
    rating: Rating;
}

interface Rating {
    rate: number;
    count: number;
}

CodePudding user response:

Could you perhaps further explain what the problem is? It's not really clear what's going wrong and what you expect to happen

Edit: I see the problem. You are actually invoking the getProducts function in your call to useQuery. You should pass a function to useQuery. If you want to be able to parameterise the function, then you should create what's called a closure, like so:

const getProducts = (id: number) => {
    return async () => {
        const rest = await fetch(`https://fakestoreapi.com/products/${id}`);
        const data: ProductApi[] = await rest.json();
        return data;
    }
}

What's happening here is, I'm return an async function that when called fetches the data from the API, and that is the function that I want to pass to useQuery

CodePudding user response:

useQuery("products", getProducts(1))

this code will invoke the function getProducts(1) during render rather than passing a function to react-query - you're actually passing the result of the function to react-query. Most example use inline functions for that matter:

useQuery("products", () => getProducts(1))

now react-query gets a function that it can invoke.

Additionally, the id should ideally be part of the queryKey, because it's a dependency to it:

const id = 1

useQuery(["products", id], () => getProducts(id))

if you do it that way, you can also potentially take advantage of the fact that react-query will inject the query key into the function you pass to it:

useQuery(["products", 1], ({ queryKey }) => getProducts(queryKey[1]))

It is best practice to only have your query function depend on things that are also inside the queryKey.

  • Related