Skip to content

Commit

Permalink
fix(nuxt): ignore prefix if clearNuxtState called w/o keys (#23483)
Browse files Browse the repository at this point in the history
  • Loading branch information
AlbertBrand authored and manniL committed Dec 11, 2023
1 parent 9ac1ccd commit 39dd5df
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 3 deletions.
2 changes: 2 additions & 0 deletions packages/nuxt/src/app/composables/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ export function clearNuxtState (
): void {
const nuxtApp = useNuxtApp()
const _allKeys = Object.keys(nuxtApp.payload.state)
.map(key => key.substring(useStateKeyPrefix.length))

const _keys: string[] = !keys
? _allKeys
: typeof keys === 'function'
Expand Down
44 changes: 41 additions & 3 deletions test/nuxt/composables.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -214,12 +214,50 @@ describe('useState', () => {
useState('key', () => 'value')
expect(Object.entries(useNuxtApp().payload.state)).toContainEqual(['$skey', 'value'])
})
})

it.todo('clearNuxtState', () => {
const state = useState(() => 'test')
describe('clearNuxtState', () => {
it('clears state in payload for single key', () => {
const key = 'clearNuxtState-test'
const state = useState(key, () => '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()
expect.soft(state.value).toBeUndefined()
expect(state1.value).toBeUndefined()
expect(state2.value).toBeUndefined()
})
})

Expand Down

0 comments on commit 39dd5df

Please sign in to comment.