fix(nuxt): ignore prefix if clearNuxtState called w/o keys (#23483)

This commit is contained in:
Albert Brand 2023-10-01 10:37:53 +02:00 committed by GitHub
parent 4063b498d3
commit df90d4234c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 43 additions and 3 deletions

View File

@ -42,6 +42,8 @@ export function clearNuxtState (
): void { ): void {
const nuxtApp = useNuxtApp() const nuxtApp = useNuxtApp()
const _allKeys = Object.keys(nuxtApp.payload.state) const _allKeys = Object.keys(nuxtApp.payload.state)
.map(key => key.substring(useStateKeyPrefix.length))
const _keys: string[] = !keys const _keys: string[] = !keys
? _allKeys ? _allKeys
: typeof keys === 'function' : typeof keys === 'function'

View File

@ -214,12 +214,50 @@ describe('useState', () => {
useState('key', () => 'value') useState('key', () => 'value')
expect(Object.entries(useNuxtApp().payload.state)).toContainEqual(['$skey', 'value']) expect(Object.entries(useNuxtApp().payload.state)).toContainEqual(['$skey', 'value'])
}) })
})
it.todo('clearNuxtState', () => { describe('clearNuxtState', () => {
const state = useState(() => 'test') it('clears state in payload for single key', () => {
const key = 'clearNuxtState-test'
const state = useState(key, () => 'test')
expect(state.value).toBe('test') expect(state.value).toBe('test')
clearNuxtState(key)
expect(state.value).toBeUndefined()
})
it('clears state in payload for array of keys', () => {
const key1 = 'clearNuxtState-test'
const key2 = 'clearNuxtState-test2'
const state1 = useState(key1, () => 'test')
const state2 = useState(key2, () => 'test')
expect(state1.value).toBe('test')
expect(state2.value).toBe('test')
clearNuxtState([key1, 'other'])
expect(state1.value).toBeUndefined()
expect(state2.value).toBe('test')
clearNuxtState([key1, key2])
expect(state1.value).toBeUndefined()
expect(state2.value).toBeUndefined()
})
it('clears state in payload for function', () => {
const key = 'clearNuxtState-test'
const state = useState(key, () => 'test')
expect(state.value).toBe('test')
clearNuxtState(() => false)
expect(state.value).toBe('test')
clearNuxtState(k => k === key)
expect(state.value).toBeUndefined()
})
it('clears all state when no key is provided', () => {
const state1 = useState('clearNuxtState-test', () => 'test')
const state2 = useState('clearNuxtState-test2', () => 'test')
expect(state1.value).toBe('test')
expect(state2.value).toBe('test')
clearNuxtState() clearNuxtState()
expect.soft(state.value).toBeUndefined() expect(state1.value).toBeUndefined()
expect(state2.value).toBeUndefined()
}) })
}) })