GraphQL
Beginner
1 min read
Apollo Client Cache Policies and Local State
Example
import { InMemoryCache, makeVar, gql, useReactiveVar } from '@apollo/client';
// ----- Reactive variable for local state -----
export const isLoggedInVar = makeVar(false);
export const cartItemsVar = makeVar([]);
// ----- Cache with field policies -----
const cache = new InMemoryCache({
typePolicies: {
Query: {
fields: {
// Cursor-based pagination merge policy
posts: {
keyArgs: ['filter'], // separate cache entries per filter
merge(existing = { edges: [] }, incoming) {
return { ...incoming, edges: [...existing.edges, ...incoming.edges] };
},
},
// Local-only field backed by reactive variable
isLoggedIn: {
read: () => isLoggedInVar(),
},
},
},
Post: {
fields: {
// Computed local field
isLiked: {
read: (existing = false) => existing,
},
},
},
},
});
// ----- Using reactive var in component -----
function LoginStatus() {
const isLoggedIn = useReactiveVar(isLoggedInVar);
return <span>{isLoggedIn ? 'Logged in' : 'Guest'}</span>;
}
// ----- @client directive reads from cache/reactive var -----
const GET_UI_STATE = gql`
query GetUIState {
isLoggedIn @client
}
`;
Related Resources
GraphQL Reference
Complete tag & property list
GraphQL How-To Guides
Step-by-step practical guides
GraphQL Exercises
Practice what you've learned
More in GraphQL