Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to put variables inside a GraphQL-tag?

Right now I have this tag below. It's static and will always get a comment with the id of 3. Is there a possible way to put a variable inside this graphQL-tag. So I can re-use the graphQL-tag, and just change the variable ID?

export const GET_COMMENTS: any = gql`
    {
        comments(id: 3) {
            userId,
            text,
            creationDate,
      }
    }
`;

Thanks in advance!

like image 470
Hannibal B. Moulvad Avatar asked Oct 01 '18 09:10

Hannibal B. Moulvad


People also ask

Is it possible to use variables in a GraphQL query?

Use GraphQL variables for type safety and self-documenting queries. GraphQL variables offer an extra layer of protection in your queries, namely type safety — meaning that a query will only accept dynamic variables of certain data types, such as String, Int (number), DateTime and so on.

How do you pass parameters in GraphQL?

When you're passing arguments in code, it's generally better to avoid constructing the whole query string yourself. Instead, you can use $ syntax to define variables in your query, and pass the variables as a separate map. . then(data => console.

How do you pass variables in GraphQL query react?

It uses React's render props pattern. import React from "react"; import { Query } from "react-apollo"; import gql from "graphql-tag"; const GET_TODOS = gql` { todos { id type } } `; const Todos = () => ( <Query query={GET_TODOS}> {({ loading, error, data }) => { if (loading) return <p>Loading...

How do you define variables in GraphQL?

Variables simplify GraphQL queries and mutations by letting you pass data separately. A GraphQL request can be split into two sections: one for the query or mutation, and another for variables. Variables can be declared after the query or mutation and are passed like arguments to a function and begin with $ .


1 Answers

Yeah, you can pass variables in the GQL queries. $xyz is kind of notation or variable name to pass variables in GQL.

export const GET_COMMENTS: any = gql`
    query GET_COMMENTS($id: Int){ // $id is the variable name
        comments(id: $id) {
            userId,
            text,
            creationDate,
      }
    }
`;
like image 88
Yashwardhan Pauranik Avatar answered Sep 30 '22 01:09

Yashwardhan Pauranik