Passing ID in GraphQL query not returning data

Viewed 75

so i'm trying to use Apollo GraphQL with React to get specific product data by its ID, but it seems to be returning undefined. I read the Apollo docs and researched, so I'm not sure what I'm doing wrong. Also, I'm able to return data from other queries that don't require an ID (like all products, for instance). Would greatly appreciate some help!

Query

export const PRODUCT = gql`
 query GetProduct($itemID: String!) {
  product(id: $itemID) {
    id
    name
    inStock
    gallery
    description
    category
    attributes {
      id
      name
      type
      items {
        displayValue
        value
      }
    }
    prices {
      currency {
        label
        symbol
      }
    }
    brand
  }
}
`;

This is where I try to return data using the ID, but to no avail:

  let myID = "ps-5";

    const { productLoading, productError, productData } = useQuery(PRODUCT, {
variables: { itemID: myID },
  });

  useEffect(() => {
      if (productData) {
        console.log("data: " + productData) // logs nothing. "Undefined" when if statement is removed
      }
  }, [])
2 Answers

It looks like the React client for Apollo uses the same API for useQuery as for Vue (with which I'm more familiar), in which case it should be used like this:

useQuery(PRODUCT, { itemID: myID })

(not { variables : { itemID : myID }})

I would have expected the backend to return an error though, because $itemID is declared as non-nullable.

It seems that you are destructing the object that useQuery() returns with the wrong object keys.

// instead of
const { productLoading, productError, productData } = '...'

// you can either use the regular keys as variables
const { loading, error, data } = '...'

// or assign aliases (useful when you use more queries on the same page)
// this way you can use the same variables as in your example
const { loading:productLoading, error:productError, data:productData } = '...'
Related