Skip to content

Commit

Permalink
fix(useStoragePlain): string
Browse files Browse the repository at this point in the history
  • Loading branch information
antfu committed Feb 11, 2020
1 parent d78a596 commit 2b88e20
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 1 deletion.
2 changes: 1 addition & 1 deletion packages/core/useStoragePlain/index.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# useStoragePlain

> Reactive LocalStorage/SessionStorage with plain string values
> Reactive LocalStorage/SessionStorage with primitives values
## Usage

Expand Down
14 changes: 14 additions & 0 deletions packages/core/useStoragePlain/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,4 +71,18 @@ describe('useStoragePlain', () => {
expect(ref.value).toBe('0')
})
})

it('string', () => {
localStorage.setItem(KEY, '0')

renderHook(() => {
const ref = useStoragePlain(KEY, '1')

expect(ref.value).toBe('0')

ref.value = '2'

expect(localStorage.setItem).toBeCalledWith(KEY, '2')
})
})
})
5 changes: 5 additions & 0 deletions packages/core/useStoragePlain/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export function useStoragePlain (key: string, defaultValue: string, storage?: St
export function useStoragePlain (key: string, defaultValue: boolean, storage?: Storage): Ref<boolean>
export function useStoragePlain (key: string, defaultValue: number, storage?: Storage): Ref<number>
export function useStoragePlain (key: string, defaultValue: null, storage?: Storage): Ref<any>
export function useStoragePlain<T extends object> (key: string, defaultValue: T, storage?: Storage): Ref<T>
export function useStoragePlain<T extends (string|number|boolean|null)> (key: string, defaultValue: T, storage: Storage = localStorage) {
const data = ref<T>(defaultValue)

Expand All @@ -22,6 +23,10 @@ export function useStoragePlain<T extends (string|number|boolean|null)> (key: st
// @ts-ignore
data.value = defaultValue === 'true'
// @ts-ignore
else if (typeof defaultValue === 'string')
// @ts-ignore
data.value = rawValue != null ? rawValue : defaultValue
// @ts-ignore
else if (!Number.isNaN(defaultValue))
// @ts-ignore
data.value = rawValue != null ? Number.parseFloat(rawValue) : defaultValue
Expand Down

0 comments on commit 2b88e20

Please sign in to comment.