Become a member
to unlock all features

Level Up!

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


    Fetch Server Data and Client-side State in One Query using React Apollo + GraphQL

    Andrew Del PreteAndrew Del Prete

    In this lesson we look at how the Apollo @client directive can be used to fetch client-side state along with server data with one query. I also show how to update the client-side state using a mutation connected to a button.

    Additional Resources Apollo Client 2.0



    Become a Member to view code

    You must be a 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




    Instructor: On the right, I have a button that triggers a request to the Pokémon GraphQL API, and renders a random Pokémon to the screen.

    The Apollo GQL tag query is fairly simple in that it only asks a server for the Pokémon image. For this example, what I'd like to do is keep track of the state and how many times I've pushed the randomize button using Apollo.

    To get started, I'll go ahead and add client state to the Apollo client instantiation with some defaults, and a resolver and mutation to update the counter. I'll name this mutation Inc Counter, and it'll just take a value and store it to the cache.

    Next, to add a new GQL query to increment the counter. Let's call this Increment Counter. This will be just the small query to call the Inc Counter mutation in the resolver.

    Notice the use of the client directive. Apollo has a nice convention to differentiate between the server and the client-side cache. This directive can be injected directly into the GQL query, and Apollo will know to retrieve or mutate that data from the client cache instead of the server.

    Long story short, it's a nice mechanism to consolidate both server-side things and client-side things all in one query. I'm going to go ahead and add the client directive for our counter into the Get Pokémon query, as well, for later use.

    The counter data is now available to our React component, so I'll pull it in and display it instead of the static zero. Since I'm using the new query component from React Apollo, I'll need to do something to pull in the Inc Counter mutation.

    There are a couple of ways we can do this. For this example, I'm going to use the GraphQL higher order component to pass Inc Counter as a property to my component and hook it up to the button.

    For this small demo, when I click the button, I'm using the re-fetch method from Apollo to pass a random Pokémon name to the GraphQL API. I'm going to make this an async function, and call the Inc Counter mutation afterwards.

    Hey, it works. Hopefully, this demonstration gives you a good idea of what you can do with the client directive, and how it can combine the server side and client side queries together.