Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add in dynamic parameters into a graphql query

I want to make a GraphQL query that takes in some data from the data field of my Vue app. However, when I set up the variables hook and try to reference the object I need by using this.object, I get a cannot read 'xxx' of undefined.

apollo: {
    question: {
      query: gql `
      query question($id: Int!) {
        question(id: $id){
          ...
        }
      }
`, variables: { id: this.presentQuestionId}
    }
  },

Uncaught TypeError: Cannot read property 'presentQuestionId' of undefined is the error message that keeps on coming up.

like image 291
Toby Avatar asked Nov 30 '25 16:11

Toby


2 Answers

variables option should be a function that returns an object like :

variables(){
    return{
     id: this.presentQuestionId
   }
}
like image 68
Boussadjra Brahim Avatar answered Dec 02 '25 05:12

Boussadjra Brahim


In pure JS I sometimes use this trick:

const opts = {foo: 1, bar: 2}
const q = gql`
    query Query {
        getSomething(
            par1: ${opts.foo}
            ${!!opts.bar ? `, par2: ${opts.bar}` : ''}
        ) {
            id
            name
        }
    }
`

If par2 defined it adds to query.

like image 40
Aleksandr Chernyi Avatar answered Dec 02 '25 07:12

Aleksandr Chernyi