Skip to content

Commit f418270

Browse files
added test for JSON.parse errors and updated the code to handle errors
Signed-off-by: Benjamin Strasser <bp.strasser@gmail.com>
1 parent c49f6b5 commit f418270

File tree

2 files changed

+26
-1
lines changed

2 files changed

+26
-1
lines changed

src/lib/utils/localstorage-writable.ts

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,13 @@ export const localStorageWritable = <T>(
1616
defaultValue?: T
1717
): LocalStorageWritable<T> => {
1818
const storedValue = browser ? localStorage.getItem(localStorageKey) : null
19-
const localStorageValue = storedValue !== null ? JSON.parse(storedValue) : null
19+
const localStorageValue = (() => {
20+
try {
21+
return storedValue !== null ? JSON.parse(storedValue) : null
22+
} catch {
23+
return null
24+
}
25+
})()
2026

2127
const initialValue: T | null = localStorageValue ?? defaultValue ?? null
2228

src/lib/utils/localstorage-writable.unit.test.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -89,6 +89,25 @@ describe('localStorageWritable', () => {
8989
expect(localStorage.getItem('testKey')).toBe(JSON.stringify(2))
9090
expect(get(store)).toBe(2)
9191
})
92+
93+
it('should initialize with default value if non-valid JSON is present in localStorage', () => {
94+
localStorage.setItem('testKey', 'invalid-json')
95+
96+
const defaultValue = 'default'
97+
const store = localStorageWritable('testKey', defaultValue)
98+
99+
expect(get(store)).toBe(defaultValue)
100+
expect(localStorage.getItem('testKey')).toBe(JSON.stringify(defaultValue))
101+
})
102+
103+
it('should initialize with null if no default value and non-valid JSON is present in localStorage', () => {
104+
localStorage.setItem('testKey', 'invalid-json')
105+
106+
const store = localStorageWritable('testKey')
107+
108+
expect(get(store)).toBe(null)
109+
expect(localStorage.getItem('testKey')).toBe(JSON.stringify(null))
110+
})
92111
})
93112

94113
describe('localStorageWritable with no browser', () => {

0 commit comments

Comments
 (0)