Home > Back-end >  Apollo GraphQL, when fetching typeerror: is undefined
Apollo GraphQL, when fetching typeerror: is undefined

Time:07-05

I'm new to GraphQL, I can't figure out why when I request to get data, for example data.category.products, I get the correct output, but for example, if I request data.category.products.prices, I will get this error: TypeError: data. category.products.prices is undefined

My Query:

query AllCategory{
  category {
    products {
      id
      prices {
        currency {
          label
        }
        amount
      }
    }
  }
}

Doesn't give errors in Playground

Here is the schema: enter image description here

And actually how I call: (this is with an error)

export default function App() {

   const {data} = useQuery(QUERIES)

   return (
    
     <div className="App">
       {data.category.products.prices.map((shop) => (
         <p key={shop.currency.label}>{shop.amount}</p>
       ))}
     </div>
   );
}

There is no error here:

{data.category.products.map((shop) => (
   <p key={shop.id}>{shop.id}</p>
))}

I`m using apollo client

CodePudding user response:

Products and prices are both arrays so you will need to flatten it or map first through your products and then through your prices.

I'd break off a component or 2. .It's not clear if you want to render product level stuff. but it would be something along these lines:


const Product = (product) => (
  <>
    {product.prices.map((price) => (
      <p key={price.currency.label}>{price.amount}</p>
    ))}
  </>
);

class App extends React.Component {
  render() {
    return (
      <>
        {data.category.products.map((product) => (
          <Product product={product} />
        ))}
      </>
    );
  }
}

I'd also recommend you generate a type safe graphql schema so that you can pick up on type issues at compile time.

You also want to ensure that data is not null by doing a truthiness check before returning as its an asynchronous call - data is defined once the graphql response is made. e.g.. return !data?null:<>......</>

useQuery also returns loading and error values from the hook which are useful

  • Related