joshnuss / svelte-persisted-store

A Svelte store that persists to localStorage

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add support for CacheStorage on iOS

mrexodia opened this issue · comments

For my app (https://calories.fitness) I'm using your library and everything works great!

However I discovered that on iOS the local storage isn't shared between the app you add to your home screen (PWA) and the website. According to https://jakub-kozak.medium.com/how-to-share-state-data-between-a-pwa-in-ios-safari-and-standalone-mode-64174a48b043 this can be worked around by using CacheStorage instead if iOS Safari is detected.

Would you accept a pull request that makes CacheStorage the preferred storage method on iOS Safari (perhaps store in both, prefer CacheStorage if found and fall back to local storage)?

Here is a working implementation of getItem and setItem with CacheStorage: https://codesandbox.io/s/cachestorage-example-forked-jvec5f

Hi @mrexodia,

Yes definitely open to this.

What do you think about making it an option? (Instead of a conditional)

Then the client code would be something like writable(key, value, { store: CachStorage }) and localStorage can be the default.

This assumes the API for localStorage and CacheStorage are identical

Yeah I guess that would work, but the CacheStorage API definitely isn't equal so the user would have to implement their own proxy (like I did in the example). Additionally there is some tricky logic (user agent matching etc.) that might be a pain to replicate for every application.

Reading about CacheStore, it seems it is designed for handling files. I'm not sure if it fits well with the paradigm of localStorage.

Just curious, why not write code to bridge the 2 in your app? something like:

import { writable } from 'svelte-local-storage-store'

// check the cache store for initial value
const cache =  await caches.open(name)
const initialValue = JSON.parse(await cache.match(key))

// define localStorageStore
const store = writable(key, initialValue)

// subscribe to changes and put in cache
store.subscribe(newValue => cache.put(key, JSON.stringify(newValue))

Would that work for your use case?

Yeah that would work, but at that point it will be easier to just implement my own version of svelte-local-storage-store since I need to do this wrapping for a few stores and it's only 50 loc. I'll give it a try and report back!

OK let me know,

You can wrap the code I shared above in a function, and you would have a reusable store.

I will close for now, but feel free to re-open if you find blockers