Join egghead, unlock knowledge.

Want more egghead?

This lesson is for members. Join us? Get access to all 3,000+ tutorials + a community with expert developers around the world.

Unlock This Lesson
Become a member
to unlock all features

Level Up!

Access all courses & lessons on egghead today and lock-in your price for life.


    Query Lists of Multiple Types using a Union in GraphQL


    Unions are used when we want a GraphQL field or list to handle multiple types of data. With a Union Type, we can define a field that could resolve completely different types of data. In this lesson, we will write a query that obtains a list of different pet types



    Become a Member to view code

    You must be a Pro Member to view code

    Access all courses and lessons, track your progress, gain confidence and expertise.

    Become a Member
    and unlock code for this lesson
    orLog In




    Instructor: In the Funded Pet Library there are a couple of extra queries here that we haven't looked at yet. One is called FamilyPets and the other one is called ExoticPets.

    Let's click on FamilyPets. We should see that there is some helpful documentation here. It says this query returns a list of FamilyPets, either a cat or a dog.

    Another useful data structure when we're working with GraphQL is called a union. We use unions when we want to return lists of multiple types.

    Whenever we query the FamilyPets field, I want to return a list of FamilyPets, either a cat or a dog. Let's go ahead and write that query.

    We're going to say FamilyPets. Let's look for the type name here. Now let me click Play. I should see Cat, Cat, Cat. As I scroll down, we should see Dog, Dog, Dog, etc.

    Unions don't have to share any fields. If I tried to query for the name field for each of these, we're going to see an error. It says cannot query field name on type FamilyPet. It's recommending that I use an inline fragment instead. Let's go ahead and do that.

    I'm going to use the inline fragment syntax to grab fields from the cat. I'll say name and sleep amount. This should give us that data for just the cats. Dogs will still only have the type name.

    If I wanted some dog-specific fields, I could get them with another in-line fragment. We'll use dot-dot-dot on dog and see their name and whether or not the dog is good.

    We use unions whenever we want to return a list of multiple types. These are really useful for things like this with FamilyPets being either a cat or a dog, ExoticPets with a rabbit or a stingray.

    You could use this for a number union that returns either an Int or a Float. A lot of different ways to use this but it's a useful data structure to know when you're working with GraphQL.