Skip to content

How to run useQuery inside forEach?

I have loop – forEach – which find productId for every element of array. I want to fetch my database by productId using apollo query. How to do it?

products.forEach(({ productId, quantity }) =>
    // fetch by 'productId'



From the rules of hooks:

Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function. By following this rule, you ensure that Hooks are called in the same order each time a component renders.

Hooks cannot be used inside a loop, so you can’t use them inside a forEach callback.

You should create a separate component for each product that only uses the useQuery hook once. You can then map over the products and return the component for each one:

const YourComponent = () => {
  return{ productId, quantity }) => (
    <Product key={productId} productId={productId} quantity={quantity} />

const Product = () => {
  const { data, error, loading } = useQuery(...)
  // render your data accordingly