-
Notifications
You must be signed in to change notification settings - Fork 0
add localstorage-writable #81
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
2598dc4
add localstorage-writable
jjnp eb13488
Update src/lib/utils/localstorage-writable.ts
jjnp c49f6b5
added unit test for localstorage-writable and fixed s small bug
benjaminstrasser f418270
added test for JSON.parse errors and updated the code to handle errors
benjaminstrasser File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| import { browser } from '$app/environment' | ||
| import { type Updater, type Writable, get, writable } from 'svelte/store' | ||
|
|
||
| export type LocalStorageWritable<T> = Writable<T | null> & { | ||
| wipe: () => void | ||
| } | ||
|
|
||
| /** | ||
| * A standard svelte-compatible writable with persistent values backed up in localStorage | ||
| * @param localStorageKey The key used for local-storage | ||
| * @param defaultValue The default value in case there is none found in localstorage | ||
| * @returns A standard writable that persists all value changes to localstorage | ||
| */ | ||
| export const localStorageWritable = <T>( | ||
| localStorageKey: string, | ||
| defaultValue?: T | ||
| ): LocalStorageWritable<T> => { | ||
| const storedValue = browser ? localStorage.getItem(localStorageKey) : null | ||
| const localStorageValue = (() => { | ||
| try { | ||
| return storedValue !== null ? JSON.parse(storedValue) : null | ||
| } catch { | ||
| return null | ||
| } | ||
| })() | ||
|
|
||
| const initialValue: T | null = localStorageValue ?? defaultValue ?? null | ||
|
|
||
| const { set, subscribe } = writable<T | null>(null) | ||
|
|
||
| const setAndStore = (value: T | null) => { | ||
| if (browser) { | ||
| localStorage.setItem(localStorageKey, JSON.stringify(value)) | ||
| } | ||
|
|
||
| set(value) | ||
| } | ||
|
|
||
| const wipe = () => { | ||
| if (browser) { | ||
| localStorage.removeItem(localStorageKey) | ||
| } | ||
|
|
||
| set(null) | ||
| } | ||
|
|
||
| setAndStore(initialValue) | ||
|
|
||
| return { | ||
| subscribe, | ||
| set: setAndStore, | ||
| wipe, | ||
| update: (updater: Updater<T | null>) => setAndStore(updater(get({ subscribe }))) | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,157 @@ | ||
| import { localStorageWritable } from './localstorage-writable' | ||
| import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' | ||
| import { get } from 'svelte/store' | ||
|
|
||
| const mockedBrowser = vi.hoisted(() => { | ||
| return vi.fn() | ||
| }) | ||
|
|
||
| vi.mock('$app/environment', () => { | ||
| return { | ||
| get browser() { | ||
| return mockedBrowser() | ||
| } | ||
| } | ||
| }) | ||
|
|
||
| const localStorageMockFactory = () => { | ||
| const store: Record<string, string> = {} | ||
|
|
||
| return { | ||
| getItem: (key: string) => store[key] || null, | ||
| setItem: (key: string, value: string) => { | ||
| store[key] = value | ||
| }, | ||
| removeItem: (key: string) => { | ||
| delete store[key] | ||
| } | ||
| } | ||
| } | ||
|
|
||
| describe('localStorageWritable', () => { | ||
| beforeEach(() => { | ||
| mockedBrowser.mockReturnValue(true) | ||
| vi.stubGlobal('localStorage', localStorageMockFactory()) | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| vi.resetAllMocks() | ||
| }) | ||
|
|
||
| it('should initialize with default value if no value in localStorage', () => { | ||
| const defaultValue = 'default' | ||
|
|
||
| const store = localStorageWritable('testKey', defaultValue) | ||
|
|
||
| expect(get(store)).toBe(defaultValue) | ||
| expect(localStorage.getItem('testKey')).toBe(JSON.stringify(defaultValue)) | ||
| }) | ||
|
|
||
| it('should initialize with value from localStorage if present', () => { | ||
| localStorage.setItem('testKey', JSON.stringify('storedValue')) | ||
|
|
||
| const store = localStorageWritable('testKey') | ||
|
|
||
| expect(get(store)).toBe('storedValue') | ||
| }) | ||
|
|
||
| it('should prioritize value from local storage over default', () => { | ||
| localStorage.setItem('testKey', JSON.stringify('storedValue')) | ||
|
|
||
| const store = localStorageWritable('testKey', 'defaultValue') | ||
|
|
||
| expect(get(store)).toBe('storedValue') | ||
| expect(localStorage.getItem('testKey')).toBe(JSON.stringify('storedValue')) | ||
| }) | ||
|
|
||
| it('should store value in localStorage when set', () => { | ||
| const store = localStorageWritable('testKey') | ||
| store.set('newValue') | ||
|
|
||
| expect(localStorage.getItem('testKey')).toBe(JSON.stringify('newValue')) | ||
| expect(get(store)).toBe('newValue') | ||
| }) | ||
|
|
||
| it('should remove value from localStorage when wipe is called', () => { | ||
| localStorage.setItem('testKey', JSON.stringify('storedValue')) | ||
|
|
||
| const store = localStorageWritable('testKey') | ||
| store.wipe() | ||
|
|
||
| expect(localStorage.getItem('testKey')).toBe(null) | ||
| expect(get(store)).toBe(null) | ||
| }) | ||
|
|
||
| it('should update the value correctly using update method', () => { | ||
| const store = localStorageWritable<number>('testKey', 1) | ||
| store.update((n) => n! + 1) | ||
|
|
||
| expect(localStorage.getItem('testKey')).toBe(JSON.stringify(2)) | ||
| expect(get(store)).toBe(2) | ||
| }) | ||
|
|
||
| it('should initialize with default value if non-valid JSON is present in localStorage', () => { | ||
| localStorage.setItem('testKey', 'invalid-json') | ||
|
|
||
| const defaultValue = 'default' | ||
| const store = localStorageWritable('testKey', defaultValue) | ||
|
|
||
| expect(get(store)).toBe(defaultValue) | ||
| expect(localStorage.getItem('testKey')).toBe(JSON.stringify(defaultValue)) | ||
| }) | ||
|
|
||
| it('should initialize with null if no default value and non-valid JSON is present in localStorage', () => { | ||
| localStorage.setItem('testKey', 'invalid-json') | ||
|
|
||
| const store = localStorageWritable('testKey') | ||
|
|
||
| expect(get(store)).toBe(null) | ||
| expect(localStorage.getItem('testKey')).toBe(JSON.stringify(null)) | ||
| }) | ||
| }) | ||
|
|
||
| describe('localStorageWritable with no browser', () => { | ||
| beforeEach(() => { | ||
| mockedBrowser.mockReturnValue(false) | ||
| vi.stubGlobal('localStorage', undefined) | ||
| }) | ||
|
|
||
| afterEach(() => { | ||
| vi.resetAllMocks() | ||
| }) | ||
|
|
||
| it('should initialize with default value', () => { | ||
| const defaultValue = 'default' | ||
| const store = localStorageWritable('testKey', defaultValue) | ||
|
|
||
| expect(get(store)).toBe(defaultValue) | ||
| }) | ||
|
|
||
| it('should initialize with null', () => { | ||
| const store = localStorageWritable('testKey') | ||
|
|
||
| expect(get(store)).toBe(null) | ||
| }) | ||
|
|
||
| it('should set value', () => { | ||
| const store = localStorageWritable('testKey') | ||
| store.set('newValue') | ||
|
|
||
| expect(get(store)).toBe('newValue') | ||
| }) | ||
|
|
||
| it('should remove value', () => { | ||
| const store = localStorageWritable('testKey') | ||
| store.set('newValue') | ||
| store.wipe() | ||
|
|
||
| expect(get(store)).toBe(null) | ||
| }) | ||
|
|
||
| it('should update the value correctly using update method', () => { | ||
| const store = localStorageWritable<number>('testKey', 1) | ||
| store.update((n) => n! + 1) | ||
|
|
||
| expect(get(store)).toBe(2) | ||
| }) | ||
| }) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
@benjaminstrasser the check here is redundant.
JSON.parse(null) === nullThere was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes you are correct! I caught that too. Problem is JSON.parse is typed as
parse(value: string)and notparse(value: string | null)even thoughparse(null) === null.See here: #81 (comment)