Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use enum in apollo-client?

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

like image 365
lidashuang Avatar asked Sep 18 '19 17:09

lidashuang


1 Answers

Prerequisites:

We must define < SomeEnumType > in our GraphQL schema (server side, no client configuration needed)

Let's assume we have defined:

enum SomeEnumType {
    OPTION1,
    OPTION2,
    OPTION3
}

We also must configure our Apollo Client in appropriate way ans connect it with the GraphQL API.

Then on client side:

export const OUR_MUTATION = gql`
    mutation ourMutation($foo: SomeEnumType){
        ourMutation(foo: $foo){
            bar
        }
    }    
`

Only doing this, you can pass enum as a variable in your query or mutation. For example using useMutation hook we can now mutate as follows:

const [ourMutation] = useMutation(OUR_MUTATION, {
        variables: {
            foo: "OPTION2"
        },

Since our type definition in gql tag equals with definition in Schema, GraphQL recognizes our variable as an enum type despite of that we give it as a string.

If we want pass enum to our variables using typescript enums we can do it as follows:

enum SomeEnumType {
    OPTION1 = 0,
    OPTION2 = 1,
    OPTION3 = 2
}

const [ourMutation] = useMutation(OUR_MUTATION, {
        variables: {
            foo: SomeEnumType[SomeEnumType.OPTION1]
        },

like image 71
Viljami Avatar answered Sep 18 '22 20:09

Viljami