Large Offline Datasets with Apollo Client

We want to be able to access boolean flags and device API results from multiple components in our app, but don’t want to maintain a separate Redux or MobX store.

Ideally, we would like the Apollo cache to be the single source of truth for all data in our client application.

— Apollo Client — Local State Managementnote: While not addressed in this article, we would also use a web worker, supported by all major browsers, to handle downloading the dataset.

The ExampleTo illustrate the core concepts, we will walk through a simplified example application.

The application is available for download.

The application first downloads and stores the dataset (a list of US cities) into IndexedDB.

Then, as the user enters text into the input, the application queries the dataset for cities that start with the text and displays the result.

Code HighlightsThe first interesting bit of code provides the loadCities (stores the dataset into IndexedDB) and searchCities (queries the dataset) functions:src/api/cities.

tsObservations:The application is written in TypeScriptThe JSON data is being loaded from a simulated API; data is stored in the application (imported JSON file) and a delay is used to simulate an asynchronous loadThe application uses the Dexie.

js library to simplify the interface to IndexedDBThe next bit of interesting code are the files that define Apollo Client’s local state:src/graphql/typeDefs.

tssrc/graphql/defaults.

tssrc/graphql/resolvers.

tsObservations:The interesting bit here is that one does not normally provide resolvers for Apollo Client’s local state queries; Apollo Client provides a default implementation that reads local state from the in-memory cacheThe last bit of interesting code queries Apollo Client local state:src/components/Cities/CitiesResults/index.

tsxObservations:By using fetchPolicy="no-cache" property we force Apollo Client into calling the query resolverAlso, this property also prevents Apollo Client from storing results in the in-memory cache (prevents filling up memory)Wrap UpNothing terribly complicated here, just a simple example to what seemed like a complicated problem at the start.

.

. More details

Leave a Reply