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.

Vano
  • 690
  • 3
  • 8
  • 25

1 Answers1

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()
Enfield Li
  • 1,952
  • 1
  • 8
  • 23
  • 1
    "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. – Vano Apr 07 '22 at 11:28