Apollo GraphQL Client With Cache

Configure an Apollo Client with in-memory cache error handling and typed queries for GraphQL data fetching.

JavascriptData Fetching

Code

javascriptsnippet
1 line
import{ApolloClient,InMemoryCache,gql}from'@apollo/client';export function createApolloClient(uri){return new ApolloClient({uri,cache:new InMemoryCache({typePolicies:{Query:{fields:{items:{merge(existing=[],incoming){return[...existing,...incoming];}}}}}}),defaultOptions:{query:{errorPolicy:'all',fetchPolicy:'cache-first'}},onError:({networkError,graphQLErrors})=>{if(networkError)console.error('network:',networkError);if(graphQLErrors)console.error('graphql:',graphQLErrors);}});}export const GET_ITEMS=gql`query GetItems($limit:Int){items(limit:$limit){id name}}`;

Inside the snippet

Apollo GraphQL Client With Cache keeps everything in the function createApolloClient.

ApolloClient, InMemoryCache, gql are the only symbols borrowed from @apollo/client — the coupling is explicit and narrow.

What comes back is a new object, not a reference to anything passed in.

Caveats

  • Plan for an install step: @apollo/client is a real dependency, resolved by the package manager.

Where you would put it to use

The main signature reads export function createApolloClient(uri)

The demo output is labeled (network:, graphql:), so every printed line maps back to its originating operation.

Callers only need createApolloClient — everything else stays internal.

Interactive Tools for This Topic

FAQ

Does `createApolloClient` modify its input?
The input survives unchanged; what you get back is a newly constructed value.
Which packages must be installed first?
Yes. The imports resolve to `@apollo/client`, which the package manager must provide.