How to Pass the Variables Dynamic in Graphql?

How to Pass the Variables Dynamic in Graphql?

what changes need to perform the code:

const data = client.mutate({
    mutation: (Query)
});

let Query = gql`
  mutation{
    create(input:{
         department:"Tester", 
         code:"Tester"
    }
    )
      {
        code,
        details,
        description,   
    }
  }`
console.log(data, "data")

how to pass input dynamically? I have my input as:

var department = {
   department:"Tester", 
   code:"Tester"
}

1 Answer

I haven't tested it, but it will work.
in react apollo-client

import { gql, useMutation } from '@apollo/client';

const Query = gql`
  mutation Create($department: String!, $code: String!) {
    create(department: $department, code: $code) {
        code
        details
        description
    }
  }
`;
const [create] = useMutation(Query);
create({ variables: { department: department_value, code: code_value } });

other way

const departmentValue = "Tester"
const codeValue = "Tester"
client.mutate({
  variables: { department: departmentValue, code:codeValue },
  mutation: gql`
    mutation Create($department: String!, $code: String!){
      create(department: $department, code: $code){
        code
        details
        description
      }
    }
  `,
})
.then(result => { console.log(result) })
.catch(error => { console.log(error) });

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Maya Lin-Takahashi
Author

Maya Lin-Takahashi

Maya is a hardware enthusiast who tests and reviews smart home devices, smartphones, wearables, and audio gear. She focuses on practical consumer value and build quality.