ticruz38/graphql-codegen-svelte-apollo

How to use with apollo-cache-persist (async apollo client setup)

i8ramin opened this issue · 2 comments

Since this library requires a default export of the apollo client, how does one use it along with the async setup of https://github.com/apollographql/apollo-cache-persist? It is possible to utilize the synchronous version of apollo-cache-persist, but if you need to utilize the async storage providers, it is not clear how one does that along with this code generator.

Figured it out. What I ended up doing is exporting an async function to restore/purge my persisted cache (the part that needs to be async. initializing apollo client itself does not). And then I call that function before starting up my app.

so inside my apolloClient.ts file I have this (along with the other normal apollo client setup stuff)

export const initPersistor = async () => {
  if (storedVersion === SCHEMA_VERSION) {
    // If the current version matches the latest version,
    // we're good to go and can restore the cache.
    await persistor.restore()
  } else {
    // Otherwise, we'll want to purge the outdated persisted cache
    // and mark ourselves as having updated to the latest version.
    await persistor.purge()
    window.localStorage.setItem(SCHEMA_VERSION_KEY, SCHEMA_VERSION)
  }
}

And the in my index.ts file where I init my Svelte app, I do this:

;(async () => {
  await initPersistor()

  new App({
    target: document.getElementById('svelte_app'),
  })
})()

indeed, this is smth that has to be done at app initialisation.
So you just export your client as default, and restore the client cache before initialising the app. Which make sense, also for those who needs sapper, it won't change anything as the cache is persisted in the client.