How to Query Enums with GraphQL using Introspection
Why use Introspection to Query Enums?
When you are working on a project that allows users to pick an option, such as a school name, it is best to query for these values from your database instead of storing them on a list. This is because if new options are added you won’t have to worry about updating a list on the frontend. Moreover, if you needed to use these values in another file you could simply call the enum query.
Introspection allows you to ask a GraphQL schema for information about what queries it supports.
In the introspection system, there are 6 introspection types we can use __Schema, __Type, __TypeKind, __Field, __InputValue, __EnumValue, __Directive. To query the enums you need to use the __Type query resolver.
For this example, I will be using an enum that stores the names of 7 universities.
Here’s how to query this enum:
The __type query resolver requires the name parameter. This parameter allows you to search your schema for items such as objects and enums based on their name.
Once you run this query your result should look like this:
This returns the name of the enum with all of its values. To use these values, store them in a variable when querying the enums. The statement should look like this:
items = data.__type.enumValues
Application on React Frontend
This example illustrates how to apply the enum query on a dropdown menu created with material-ui components. The enum items are stored in the list menuItems and then passed to the dropdown component with the map method. Thus, every time the user interacts with the dropdown menu the query will be called and all the values stored in the menuItems will be displayed.
The end result should look like this
Using introspection is easy and it’s a great way to reduce the number of variables that store the same information in your database. The best thing about using introspection is that no changes need to be done to the frontend to update the list being displayed.
If you want to learn more about introspection, I found this article helpful, GraphQL Introspection and Introspection Queries
If you want to learn more about GraphQL, I found these helpful concepts, 36-GraphQL-concepts.