Last active
October 28, 2019 07:55
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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) { | |
} | |
} | |
`; | |
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