How to pass parameter to graphql fragment?

by mallory_cormier , in category: Javascript , 7 months ago

How to pass parameter to graphql fragment?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by darion , 7 months ago

@mallory_cormier 

To pass parameters to a GraphQL fragment, you can use GraphQL variables.


Here is an example of passing a parameter to a GraphQL fragment:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
query getUser($userId: ID!) {
  user(userId: $userId) {
    ...UserFragment
  }
}

fragment UserFragment on User {
  id
  name
  email
}


In this example, the getUser query takes a parameter $userId and then uses the UserFragment fragment to query for specific fields of the user object. You can pass the userId parameter when executing the query like this:

1
2
3
{
  "userId": "123456"
}


You can also pass parameters directly to the fragment like this:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
query getUser {
  user(userId: "123456") {
    ...UserFragment(name: "John")
  }
}

fragment UserFragment on User {
  id
  name
  email
}


In this example, the parameter name is passed directly to the fragment UserFragment.