Simple Apollo Local State Example

Simple Apollo Local State Example

This is a very simple example of using Apollo Client's new local state functionality. In this example I query a publicly accessible Pokemon GraphQL API along side a local state query that resolves static user data from a JavaScript object.

This is the simplest example of the using local state I could come up with. Enjoy!

Usage

Option 1: Play in CodeSandbox

Option 2: Copy the code

import React from "react";
import ReactDOM from "react-dom";
import { ApolloClient } from "apollo-client";
import { InMemoryCache } from "apollo-cache-inmemory";
import { HttpLink } from "apollo-link-http";
import { ApolloProvider, Query } from "react-apollo";
import gql from "graphql-tag";

// This is your average React Component just querying GraphQL
// the only difference is you need to add "@client" to any
// piece of query data that is coming from local state
function App() {
  const GET_POKEMONS = gql(`
    query getPokemons {
      pokemons(first: 10) {
        name
      }
      user @client {
        name
      }
    }
  `);

  const renderContent = ({ loading, error, data }) => {
    if (loading) return <h4>Loading...</h4>;
    if (error) return <h4>Error...</h4>;

    return (
      <div className="App">
        <h1>Hello {data.user.name}</h1>
        <h2>These are your Pokemon</h2>
        <ul>
          {data.pokemons.map(pokemon => (
            <li key={pokemon.name}>{pokemon.name}</li>
          ))}
        </ul>
      </div>
    );
  };

  return <Query query={GET_POKEMONS}>{renderContent}</Query>;
}

// You can define resolvers + typeDefs and/or link
// they do not depend on each other.
// When you add resolvers + typeDefs you're just
// extending your remote GraphQL API with one that
// is defined locally
const client = new ApolloClient({
  cache: new InMemoryCache(),
  link: new HttpLink({ uri: "https://graphql-pokemon.now.sh/graphql" }),
  resolvers: {
    Query: {
      user: () => ({ __typename: "User", name: "Trainer" })
    }
  },
  typeDefs: `
    type Query {
      user: {
        name: String
      }
    }
  `
});

ReactDOM.render(
  <ApolloProvider client={client}>
    <App />
  </ApolloProvider>,
  document.getElementById("root")
);

Resources