How to use GraphQL enums in frontend code (e.g. in a <select>)?

2.2k Views Asked by At

I have a simple GraphQL enum defined like the following:

enum PassType {
    DailyFit
    StarterFit
    MonthlyFit
    QuarterlyFit
    DoubleFit
    MultiFit10
    MultiFit20
}

I would like to reuse these values in a <select> tag. I'm using Apollo and AWS Appync as a GraphQL infrastructure. Is there a way to get these from the Apollo client without duplicating them on the frontend manually?

1

There are 1 best solutions below

1
Daniel Rearden On BEST ANSWER

You can utilize an introspection query to fetch information about any particular type in your schema, including enums. Utilizing Apollo's Query component, this would look something like:

const PASS_TYPE_QUERY = gql`
  query GetEnum {
    __type(name: "PassType") {
      enumValues {
        name
      }
    }
  }
`

<Query query={PASS_TYPE_QUERY}>
  {({ data }) => {
    // Handle loading/errors as usual
    if (!data.__type) {
      return null
    }
    return (
      <select>
        {data.__type.enumValues.map(enumValue => (
          <option value={enumValue.name}>{enumValue.name}</option>
        ))}   
      </select>
    )
  }}
</Query>