Concluding Union Types

Implement a union type query in a React application, and test what you have learned.

Summarizing union types

Here is a quick recap of union types:

  • Our GraphQL API returns a union type for a user field.

  • A union-typed field will return a selection of objects that matches one of the types from the union. For our React application, the API returns either a User type or a SuspendedUser type.

  • To know what type we are getting back from our API, we use the special __typename metafield that GraphQL provides.. If we request the badboy user, we will get a user back with a __typename of SuspendedUser. And if we request goodie-goodie, we will get back a user with the __typename of User. We can then use that __typename field to determine which component to render.

  • Using GraphQL Code Generator here will give us a type for the user query. We can then extract a type for each user with the Extract typescript feature.

Get hands-on with 1200+ tech skills courses.