KD1
KD1

Reputation: 117

Vue Apollo query single item with ID

I am trying to query a single product using Vue Apollo but I don't understand what I am doing wrong. In the console I get the following error: Observable.js?a7b2:65 Uncaught TypeError: Cannot read property 'product' of undefined

Query:

export const getProduct = gql`
  query getProduct ($productId: ID!) {
    product (where: {id: $productId}) {
      id
      title
      description
      price
      productDetails {
        html
      }
      productAssets {
        id
        url
      }
    }
  }
`;

Component:

apollo: {
  $loadingKey: 'loading',
  products: {
    query: getProduct,
    variables: {
      $productId: 'ABC123',
    },
    result ({data}) {
      this.loading = false;
      this.product = data.product;
      this.assets = data.assets;
    },
    error () {
      this.error = true;
      this.sentryError = error;
    },
  },
},

If I however hard code the ID in, it works.

export const product = gql`
  query getProduct ($product: ID!) {
    product (where: {id: "ABC123"}) {
      id
      title
      description
      price
      productDetails {
        html
      }
      productAssets {
        id
        url
      }
    }
  }
`;

I don't see what I am missing, any help will be greatly appreciate.

Upvotes: 0

Views: 872

Answers (1)

Ezra Siton
Ezra Siton

Reputation: 7741

First, Arguments can be required. You set $product: ID! (by !) to be required.

Playground - options to run the query:

1. QUERY by "hard code"

"If I however hard code the ID in, it works"

This is the first way (You declare the argument manually in your Query).

2. "QUERY VARIABLES" tab

Click on [QUERY VARIABLES] and pass the vars Variables in JSON format.

enter image description here

graphql-variables Extra reading:

Vue - Query with parameters:

// Apollo-specific options
apollo: {
  // Query with parameters
  ping: {
    // gql query
    query: gql`query PingMessage($message: String!) {
      ping(message: $message)
    }`,
    // Static parameters
    variables: {
      message: 'Meow',
    },
  },
},

https://apollo.vuejs.org/guide/apollo/queries.html#query-with-parameters

Upvotes: 1

Related Questions