How to use constant data instead of query field name?

1.3k views Asked by At

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

There are 1 answers

1
Enfield Li On

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()