Search code examples
graphqlapolloappsync-apollo-client

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


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?


Solution

  • 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>