Skip to content

Instantly share code, notes, and snippets.

@aakash14goplani
Last active June 9, 2023 06:58
Show Gist options
  • Save aakash14goplani/63de90b7887e62eaaf748cc7db86efc3 to your computer and use it in GitHub Desktop.
Save aakash14goplani/63de90b7887e62eaaf748cc7db86efc3 to your computer and use it in GitHub Desktop.
Custom Svelte Store for saving data in local-storage

Credits: https://github.com/angrytongan/svelte-summit-2021/blob/main/src/store.js

import { writable } from 'svelte/store';
import LZString from 'lz-string';

export const ourStore = (name, initialValue, toStorage = [], fromStorage = []) => {
    if (window?.localStorage) {
        const storedValue = window.localStorage.getItem(name);

        if (storedValue) {
            initialValue = fromStorage.reduce((acc, fn) => fn(acc), storedValue);
        }
    }

    const { subscribe, set } = writable(initialValue);

    return {
        subscribe,

        set: (x) => {
            if (window?.localStorage) {
                window.localStorage.setItem(name, toStorage.reduce((acc, fn) => fn(acc), x));
            }
            set(x);
        },
    };
};

export const someText = ourStore('someText', '');
export const anObject = ourStore(
    'anObject',
    {
        a: 12345,
        b: true,
        c: 'this is a string',
    },
    [ JSON.stringify ],
    [ JSON.parse ],
);
export const aCompressedObject = ourStore(
    'aCompressedObject',
    {
        a: 12345,
        b: true,
        c: 'this is a string',
    },
    [ JSON.stringify, LZString.compress ],
    [ LZString.decompress, JSON.parse ],
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment