It's easy to pass a parameter to a GraphQL query. But what about GraphQL fragments?
This code contains some perfectly normal querying with a parameter (itemId) and a hint at what I attempt to do (includeExtraResults) :
export const GET_ITEM = gql`
query GetItem($itemId: ID!, $includeExtraResults:BOOLEAN) {
container {
item(itemId: $itemId) {
itemId
someField
innerItem(someExtraOption: $includeExtraResults) {
...InnerItemFragment
}
}
}
}
${INNER_ITEM_FRAGMENT}
`;
export const INNER_ITEM_FRAGMENT = gql`
fragment InnerItemFragment on InnerItemType {
innerItemId
innerInnerItem(someExtraOption: $includeExtraResults) {
someFields
}
}
${INNER_INNER_ITEM_FRAGMENT}
`;
export const INNER_INNER_ITEM_FRAGMENT = gql`
/* (not detailed here) */
`;
When inner-inner items get automatically queried as part of inner items, I don't want them to return the field based upon which the filter works. The client doesn't know the logic either. Instead I want to use the parameter, and the logic is decided on server side.
Still, their query is implemented in a way that it wants the (optional) parameter "includeExtraResults", which is passed to GetItem in the first place.
So, is there a way to pass "includeExtraResults" to the inner fragment? What should be changed for this to make sense? In real life this is a complex system with many levels of inner fragments.
It's not the same, but still related:
You can use query's variables inside Fragments:
query HeroComparison($first: Int = 3) {
leftComparison: hero(episode: EMPIRE) {
...comparisonFields
}
rightComparison: hero(episode: JEDI) {
...comparisonFields
}
}
fragment comparisonFields on Character {
name
friendsConnection(first: $first) {
totalCount
edges {
node {
name
}
}
}
}
This info from the official guide
As outlined here, you have to explicitly enable fragment variables before using them:
import { enableExperimentalFragmentVariables } from 'graphql-tag'
enableExperimentalFragmentVariables()
That should at least let you use variables defined in your operation inside included fragments. Please note that this still is an experimental feature that's not officially part of the spec -- see this issue for the ongoing conversation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With