Concluding Union Types
Implement a union type query in a React application, and test what you have learned.
We'll cover the following
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 aSuspendedUser
type.To know what type we are getting back from our API, we use the special
__typename
metafield that GraphQL provides.. If we request thebadboy
user, we will get a user back with a__typename
ofSuspendedUser
. And if we requestgoodie-goodie
, we will get back a user with the__typename
ofUser
. 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 1400+ tech skills courses.