1

In my React(Apollo client) App, for creating queries I am using gql`` tag from graphql-tag package, I am wandering if following is somehow possible to achieve:

const bookField = 'books'
const GET_BOOKS = gql`
query getBooks {
   ${bookField} {
    id
    title
 }
`

So basically to use constant value as a query name? After this kind of change graphql-codegen doesn't generates query and related types,hooks... any ideas?

Thank you.

1 Answer 1

0

If you wanna query field conditionally, the way I see it, is to create different Fragment, and based on that, with the hooks auto generated by apollo client and code-gen, you can query different field.

// Let's say in this seanario:
const bookField = condition ? 'books' : "otherField"

const GET_BOOKS = gql`
query getBooks {
   ${bookField} {
    id
    title
 }
`

// This should be put in useEffect
// auto gen hooks
const bookField = condition ? useGetBooksQuery() : useGetOtherFieldQuery()
Sign up to request clarification or add additional context in comments.

1 Comment

"books" is query name not a field of query, so I just need to extract it in constant, I am not planing to use different name for bookField. BTW thanks for your time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.