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

Hannibal B. Moulvad picture Hannibal B. Moulvad · Oct 1, 2018 · Viewed 7.9k times · Source

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!

Answer

Yashwardhan Pauranik picture Yashwardhan Pauranik · Oct 1, 2018

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,
      }
    }
`;