import {useCallback, useEffect, useState} from 'react' import { ApolloClient, ApolloProvider, NormalizedCacheObject, useQuery, } from '@apollo/client'; import gql from 'graphql-tag'; import { InMemoryCache } from '@apollo/client/core'; import { CachePersistor, LocalStorageWrapper } from 'apollo3-cache-persist'; import styles from './App.module.css'; const episodesGQL = gql` query episodes { episodes { results { episode id name air_date } } } `; type EpisodesQuery = { episodes: { results: { episode: string; id: string; name: string; air_date: string; }[]; } }; const Launches = () => { const { error, data, loading } = useQuery(episodesGQL, { fetchPolicy: 'cache-and-network', }); if (!data) { // we don't have data yet if (loading) { // but we're loading some return

Loading initial data...

; } if (error) { // and we have an error return

Error loading data :(

; } return

Unknown error :(

; } return (
{loading ?

Loading fresh data...

: null} {data.episodes.results.map(episode => (
{episode.episode}: {episode.name}
{episode.air_date}
))}
); }; const App = () => { const [client, setClient] = useState>(); const [persistor, setPersistor] = useState< CachePersistor >(); useEffect(() => { async function init() { const cache = new InMemoryCache(); let newPersistor = new CachePersistor({ cache, storage: new LocalStorageWrapper(window.localStorage), debug: true, trigger: 'write', }); await newPersistor.restore(); setPersistor(newPersistor); setClient( new ApolloClient({ uri: 'https://rickandmortyapi.com/graphql', cache, }), ); } init().catch(console.error); }, []); const clearCache = useCallback(() => { if (!persistor) { return; } persistor.purge(); }, [persistor]); const reload = useCallback(() => { window.location.reload(); }, []); if (!client) { return

Initializing app...

; } return (

Example controls

Use the following buttons to control apollo3-cache-persist.

Once you've loaded the initial data, you should see "Loading fresh data" followed by the list of cached Launches every time you reload the page.

Clear cache should remove everything from the localstorage, so that when you reload the page, you should see "Loading initial data..." for a moment.

Debugging output is enabled,{' '} make sure to open Developer console to see what's going on. You can see the cached data under{' '} Application → Local Storage.

); }; export default App