Setup Apollo for Offline | Part 1

Gary Ryan
Hired Engineering
Published in
2 min readAug 30, 2019
Apollo Offline

Introduction

This tutorial walks through 3 steps to setup the Apollo client for offline web apps. Part 1 covers how to cache queries for offline use. This might be all you need. If you need to support offline mutations, this is covered in part 2 (coming soon!).

Step 1: Setup an Apollo Client

Setup an Apollo client with apollo-link-http and apollo-cache-inmemory .

Setup an Apollo Client

Step 2: Add the cache persister

The apollo-cache-persist library adds offline persistence to your in memory cache.

We use localStorage as the storage layer. Persist cache will simply call cache.extract() and write the returned object to local storage.
When persistCache is called it will check local storage. If a persisted cache is found it will restore it await cache.restore(data) .

Add the cache persister

Step 3: Wait for the cache to restore

You may have noticed that we need to await the persistCache function. This is because the cache needs to perform an asynchronous restore operation.

To avoid rendering the app too soon, we should display a loading screen until the cache is ready.

Wait for the cache to restore

Summary

In this tutorial we setup an Apollo client, added cache persistence, and created an App component which displays a loading state while waiting for the cache to be ready.

🎉🎉 Congratulations! you now have offline support for your Apollo queries.

Next Steps

Supporting offline queries is great, and in most cases all we need. However, sometimes we may want to enable offline mutations. This is a much trickier task, and deserves it own tutorial. This will be covered in part 2 (coming soone!).

--

--