Apollo GraphQL Client With Cache
Configure an Apollo Client with in-memory cache error handling and typed queries for GraphQL data fetching.
Code
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/clientis 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
GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.GraphQL SDL to TypeScript ConverterParse GraphQL SDL type, input, interface, enum, union, and scalar definitions into strict TypeScript interfaces and literal unions locally.Cache-Control BuilderCompose a valid Cache-Control header from directives such as no-store, private, max-age, and immutable.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.