how to use enum in apollo-client?

lidashuang picture lidashuang · Sep 18, 2019 · Viewed 7.4k times · Source

the enum define in OrderTypesEnum.gql

enum OrderTypes {
  full_buy
  pink_buy
}

import OrderTypesEnum.gql file

import OrderTypes from '@/graphql/OrderTypesEnum.gql'`

but, How to get enum in code ?

I use OrderTypes.full_buy get some error:

   self.$apollo.mutate({
        mutation: createOrder,
        variables: {
          subjectId: self.subject.id,
          types: OrderTypes.full_buy
        }
      })
Mutation createOrderMutation error: Invariant Violation: Schema type definitions not allowed in queries. Found: "EnumTypeDefinition"

the inspect of OrderTypes type enum

enter image description here

Answer

Edmundo Rodrigues picture Edmundo Rodrigues · Sep 18, 2019

As the error message is suggesting, Schema type definitions not allowed in queries., you can't add an enum definition in an operation document (ExecutableDefinition). You can only have operations (query, mutation, or subscription), or fragments definitions. That is, this is invalid:

enum OrderTypes {
  FULL_BUY
  PINK_BUY
}

mutation createOrderMutation {
  ...
}

If you want to define a local enum on your client, you can use the typeDefs property during ApolloClient initialization:

const client = new ApolloClient({
  cache,
  typeDefs: gql`
    enum OrderTypes {
      FULL_BUY,
      PINK_BUY
    }
  `,
});

And then you'll be able to see the OrderTypes enum on client-side introspection (i.e Apollo extension).

Pay attention to the client-side highlight: if you try to send a request with this enum for a non-client field (i.e without the @client directive) and it makes through your server, you'll get a schema error saying that the enum type does not exist, unless you define it on your backend.