Skip to content
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

feat(useStorage): mergeDefaults option #1957

Merged
merged 8 commits into from Jul 24, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 6 additions & 0 deletions packages/core/useStorage/index.test.ts
Expand Up @@ -347,5 +347,11 @@ describe('useStorage', () => {
storage.setItem(KEY, JSON.stringify([1]))
const arrayRef = useStorage(KEY, [2], storage, { mergeDefaults: true })
expect(JSON.stringify(arrayRef.value)).toBe(JSON.stringify([1, 2]))

// custom function
storage.setItem(KEY, JSON.stringify([{ a: 1 }]))
const initial = [{ a: 3 }]
const customRef = useStorage(KEY, initial, storage, { mergeDefaults: () => ([{ a: 2 }, ...initial]) })
expect(JSON.stringify(customRef.value)).toBe(JSON.stringify([{ a: 2 }, { a: 3 }]))
})
})
13 changes: 8 additions & 5 deletions packages/core/useStorage/index.ts
@@ -1,5 +1,5 @@
import type { Awaitable, ConfigurableEventFilter, ConfigurableFlush, MaybeComputedRef, RemovableRef } from '@vueuse/shared'
import { pausableWatch, resolveUnref } from '@vueuse/shared'
import { isFunction, pausableWatch, resolveUnref } from '@vueuse/shared'
import { ref, shallowRef } from 'vue-demi'
import type { StorageLike } from '../ssr-handlers'
import { getSSRHandler } from '../ssr-handlers'
Expand Down Expand Up @@ -77,10 +77,12 @@ export interface UseStorageOptions<T> extends ConfigurableEventFilter, Configura

/**
* Merge the default value to the storage
* Note: It'll be a shallow merge when set to true
* You can provide a custom function for deep merge
*
* @default false
*/
mergeDefaults?: boolean
mergeDefaults?: boolean | ((storage: StorageLike, defaults: T) => T)

/**
* Custom data serialization
Expand Down Expand Up @@ -195,10 +197,11 @@ export function useStorage<T extends(string | number | boolean | object | null)>
return rawInit
}
else if (!event && mergeDefaults) {
if (type === 'object') {
const value = serializer.read(rawValue)
const value = serializer.read(rawValue)
if (isFunction(mergeDefaults))
return mergeDefaults(storage!, value)
webfansplz marked this conversation as resolved.
Show resolved Hide resolved
else if (type === 'object')
return Array.isArray(value) ? [...value, ...<[]>rawInit] : { ...value, ...<object>rawInit }
}
return rawInit
}
else if (typeof rawValue !== 'string') {
Expand Down