0
0
GraphQLquery~5 mins

Apollo Client setup in GraphQL

Choose your learning style9 modes available
Introduction

Apollo Client helps you easily get data from a GraphQL server and use it in your app.

You want to fetch data from a GraphQL API in your web or mobile app.
You need to manage and cache data from a server to improve app speed.
You want to update your app UI automatically when data changes.
You want to simplify sending queries and mutations to a GraphQL server.
Syntax
GraphQL
import { ApolloClient, InMemoryCache } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://your-graphql-endpoint.com/graphql',
  cache: new InMemoryCache()
});

uri is the URL of your GraphQL server.

InMemoryCache stores data locally to avoid repeated requests.

Examples
This example sets up Apollo Client to fetch country data from a public GraphQL API.
GraphQL
import { ApolloClient, InMemoryCache } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://countries.trevorblades.com/',
  cache: new InMemoryCache()
});
This example adds an authorization header for APIs that need a token.
GraphQL
import { ApolloClient, InMemoryCache, createHttpLink } from '@apollo/client';
import { setContext } from '@apollo/client/link/context';

const httpLink = createHttpLink({
  uri: 'https://myapi.example.com/graphql'
});

const authLink = setContext((_, { headers }) => {
  return {
    headers: {
      ...headers,
      authorization: 'Bearer YOUR_TOKEN'
    }
  };
});

const client = new ApolloClient({
  link: authLink.concat(httpLink),
  cache: new InMemoryCache()
});
Sample Program

This program sets up Apollo Client and fetches data about the United States, then prints the result.

GraphQL
import { ApolloClient, InMemoryCache, gql } from '@apollo/client';

const client = new ApolloClient({
  uri: 'https://countries.trevorblades.com/',
  cache: new InMemoryCache()
});

client.query({
  query: gql`
    {
      country(code: "US") {
        name
        capital
        currency
      }
    }
  `
}).then(result => console.log(result.data));
OutputSuccess
Important Notes

Always set the correct uri for your GraphQL server.

Use InMemoryCache to improve performance by caching results.

You can add headers like authorization tokens if your API requires it.

Summary

Apollo Client connects your app to a GraphQL server easily.

Set the server URL with uri and use InMemoryCache to store data.

Use the client to send queries and get data for your app.