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 2 commits
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
17 changes: 17 additions & 0 deletions packages/core/useStorage/index.test.ts
Expand Up @@ -331,4 +331,21 @@ describe('useStorage', () => {

expect(storage.removeItem).toBeCalledWith(KEY)
})

it('mergeDefaults option', async () => {
// basic
storage.setItem(KEY, '0')
const basicRef = useStorage(KEY, 1, storage, { mergeDefaults: true })
expect(basicRef.value).toBe(1)

// object
storage.setItem(KEY, JSON.stringify({ a: 1 }))
const objectRef = useStorage(KEY, { a: 2, b: 3 }, storage, { mergeDefaults: true })
expect(JSON.stringify(objectRef.value)).toBe(JSON.stringify({ a: 2, b: 3 }))

// array
storage.setItem(KEY, JSON.stringify([1]))
const arrayRef = useStorage(KEY, [2], storage, { mergeDefaults: true })
expect(JSON.stringify(arrayRef.value)).toBe(JSON.stringify([1, 2]))
})
})
15 changes: 15 additions & 0 deletions packages/core/useStorage/index.ts
Expand Up @@ -75,6 +75,13 @@ export interface UseStorageOptions<T> extends ConfigurableEventFilter, Configura
*/
writeDefaults?: boolean

/**
* Merge the default value to the storage
*
* @default false
*/
mergeDefaults?: boolean
webfansplz marked this conversation as resolved.
Show resolved Hide resolved

/**
* Custom data serialization
*/
Expand Down Expand Up @@ -121,6 +128,7 @@ export function useStorage<T extends(string | number | boolean | object | null)>
deep = true,
listenToStorageChanges = true,
writeDefaults = true,
mergeDefaults = false,
shallow,
window = defaultWindow,
eventFilter,
Expand Down Expand Up @@ -186,6 +194,13 @@ export function useStorage<T extends(string | number | boolean | object | null)>
storage!.setItem(key, serializer.write(rawInit))
return rawInit
}
else if (!event && mergeDefaults) {
if (type === 'object') {
const value = serializer.read(rawValue)
return Array.isArray(value) ? [...value, ...<[]>rawInit] : { ...value, ...<object>rawInit }
}
return rawInit
}
else if (typeof rawValue !== 'string') {
return rawValue
}
Expand Down