Skip to content

Instantly share code, notes, and snippets.

@khromov
Last active August 12, 2023 22:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save khromov/689ab58392d93139a94013c2db384e20 to your computer and use it in GitHub Desktop.
Save khromov/689ab58392d93139a94013c2db384e20 to your computer and use it in GitHub Desktop.
Capacitor Preferences API Store
import { get, writable, type Writable } from 'svelte/store';
import { getObject, setObject } from '$lib/capacitor';
export interface CapacitorStore<T> extends Writable<T> {
loadInitial: () => Promise<boolean>;
}
// Capacitor stores can not have null as a default value because that is what Capacitor returns by default :shrug:
export function createCapacitorStore<T>(key: string, initialValue: T): CapacitorStore<T> {
// Create a normal Writable store that will mirror our value in the Capacitor store
const { subscribe, set: originalSet, update: originalUpdate } = writable<T>(initialValue);
async function loadInitial(): Promise<boolean> {
console.log('✨ Initializing Capacitor store:', key);
const nativeValue = await getObject(key);
if (nativeValue !== null) {
originalSet(nativeValue);
return true;
} else {
return false; // Keep in mind that loadInitial will be null if there was an error OR the value was not set yet in the native store
}
}
async function set(value: T): Promise<boolean> {
const ok = await setObject(key, value);
if (ok) {
originalSet(value);
return true;
} else {
return false;
}
}
async function update(updater: (value: T) => T): Promise<boolean> {
const resolvedUpdaterCallback = updater(get({ subscribe })); // Get the latest Writable value
const ok = await setObject(key, resolvedUpdaterCallback);
if (ok) {
originalUpdate(() => resolvedUpdaterCallback);
return true;
} else {
return false;
}
}
return {
subscribe, // We use the original subscribe function
set,
update,
loadInitial
};
}
import { Preferences } from '@capacitor/preferences';
export const setObject = async (key: string, value: any): Promise<boolean> => {
try {
await Preferences.set({
key,
value: JSON.stringify(value)
});
return true;
} catch (e) {
console.error('Failed to setObject', e);
return false;
}
};
export const getObject = async (key: string): Promise<any | null> => {
try {
const ret = await Preferences.get({ key });
if (ret?.value) {
return JSON.parse(ret.value);
} else {
return null;
}
} catch (e) {
console.error('Failed to getObject', e);
return null;
}
};
export const deleteObject = async (key: string): Promise<boolean> => {
try {
await Preferences.remove({ key });
return true;
} catch (e) {
console.error('Failed to deleteObject', e);
return false;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment