diff options
| author | Fuwn <[email protected]> | 2025-06-12 22:06:31 -0700 |
|---|---|---|
| committer | Fuwn <[email protected]> | 2025-06-12 22:06:31 -0700 |
| commit | e8612618fb20f779ebe2e85edf32d71961d2f1d4 (patch) | |
| tree | fa8565afb8584bbf55f4f4d496c2c350a5a25210 /src/stores/identity.ts | |
| parent | refactor(List): Simplify get-set structure of stateBin usage (diff) | |
| download | due.moe-e8612618fb20f779ebe2e85edf32d71961d2f1d4.tar.xz due.moe-e8612618fb20f779ebe2e85edf32d71961d2f1d4.zip | |
feat: Move remaining localStorage usages to localforage
Diffstat (limited to 'src/stores/identity.ts')
| -rw-r--r-- | src/stores/identity.ts | 43 |
1 files changed, 22 insertions, 21 deletions
diff --git a/src/stores/identity.ts b/src/stores/identity.ts index 2618d744..596c7176 100644 --- a/src/stores/identity.ts +++ b/src/stores/identity.ts @@ -1,6 +1,7 @@ import { browser } from '$app/environment'; import type { UserIdentity } from '$lib/Data/AniList/identity'; import { writable } from 'svelte/store'; +import localforage from 'localforage'; export const defaultIdentity: UserIdentity = { name: '', @@ -9,22 +10,26 @@ export const defaultIdentity: UserIdentity = { }; const createStore = () => { - const { subscribe, set, update } = writable<UserIdentity>( - JSON.parse( - browser - ? (localStorage.getItem('identity') ?? JSON.stringify(defaultIdentity)) - : JSON.stringify(defaultIdentity) - ) - ); - let state: UserIdentity; + const store = writable<UserIdentity>(defaultIdentity); + let state: UserIdentity = defaultIdentity; - subscribe((value) => (state = value)); + if (browser) + localforage.getItem<UserIdentity>('identity').then((value) => { + if (value && typeof value === 'object') store.set(value); + }); + + store.subscribe((value) => { + state = value; + + if (browser) localforage.setItem('identity', value); + }); return { - subscribe, - set, - update, - reset: () => set(defaultIdentity), + subscribe: store.subscribe, + set: store.set, + update: store.update, + reset: () => store.set(defaultIdentity), + get: () => { const keys = Object.keys(defaultIdentity); const identityKeys = Object.keys(state); @@ -32,22 +37,18 @@ const createStore = () => { for (const key of keys) if (!identityKeys.includes(key)) - (updatedIdentity[key as keyof UserIdentity] as unknown) = - defaultIdentity[key as keyof UserIdentity]; + updatedIdentity[key as keyof UserIdentity] = defaultIdentity[key as keyof UserIdentity]; - if (browser) localStorage.setItem('identity', JSON.stringify(updatedIdentity)); + if (browser) localforage.setItem('identity', updatedIdentity); return updatedIdentity; }, + setKey: (key: keyof UserIdentity, value: unknown) => - update((identity) => ({ ...identity, [key]: value })) + store.update((identity) => ({ ...identity, [key]: value })) }; }; const identity = createStore(); -identity.subscribe((value) => { - if (browser) localStorage.setItem('identity', JSON.stringify(value)); -}); - export default identity; |