Search⌘ K

Concluding Union Types

Explore how to effectively query and handle union types in a React application using Apollo Client. Learn to leverage the __typename field to distinguish between different data types, apply TypeScript features for type safety, and render appropriate React components for each union type returned by a GraphQL API.

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