Skip to content

Instantly share code, notes, and snippets.

@brookback
Last active October 28, 2019 07:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brookback/b9155ae9b6e700fdcefa02f27b32bb24 to your computer and use it in GitHub Desktop.
Save brookback/b9155ae9b6e700fdcefa02f27b32bb24 to your computer and use it in GitHub Desktop.
Conditionally fetching a GraphQL field based on the presence of required variable.
/*
This query will crash when run if incoming userId prop is undefined. It's because
it's marked as required for the `user(id)` field. So that will force me to mark it
as required as a variable in my `Foo` client query below.
But I want to *conditionally* include the whole user field if only if userId prop
is a string in the component.
How?!
The goal is to not have to do two queries – one for when you're logged in, and one
for when logged out.
- Note that @include/@skip directives only take booleans as their parameters.
- Passing empty string as `userId` will work. But elegant? :thinking_face:
*/
const QUERY = /* GraphQL */`
query Foo($userId: ID!, $isLoggedIn: Boolean!) {
publicData {
name
}
# 'id' is required on the 'user' field; thus I can't make $userId optional
# in the 'Foo' query.
user(id: $userId) @include(if: $isLoggedIn) {
email
}
}
`;
const MyComponent = (props) => {
const res = doQuery(QUERY, {
variables: {
userId: props.userId, // Passing empty string here and `isLoggedIn: false` will work.
isLoggedIn: !!props.userId,
}
});
// ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment