[🚀Apollo] Cache - Advanced Topics


アポロ公式ドキュメントを翻訳しました.

Bypassing the cache

const { loading, error, data } = useQuery(GET_DOGS, {
  fetchPolicy: "no-cache"
});

Persisting the cache

import { AsyncStorage } from 'react-native';
import { InMemoryCache } from '@apollo/client';
import { persistCache } from 'apollo3-cache-persist';

const cache = new InMemoryCache();

persistCache({
  cache,
  storage: AsyncStorage,
}).then(() => {
  // Continue setting up Apollo Client as usual.
})

Resetting the cache

  • To reset the cache without refetching active queries, use client.clearStore() instead of client.resetStore().
  • export default withApollo(graphql(PROFILE_QUERY, {
      props: ({ data: { loading, currentUser }, ownProps: { client }}) => ({
        loading,
        currentUser,
        resetOnLogout: async () => client.resetStore(),
      }),
    })(Profile));

    Cache redirects

    import { ApolloClient, InMemoryCache } from '@apollo/client';
    
    const client = new ApolloClient({
      cache: new InMemoryCache({
        typePolicies: {
          Query: {
            fields: {
              book: {
                read(_, { args, toReference }) {
                  return toReference({
                    __typename: 'Book',
                    id: args.id,
                  });
                }
              }
            }
          }
        }
      }
    });

    Pagination utilities

  • Incremental loading: fetchMore
  • The @connection directive