Skip to content

Commit 52f959e

Browse files
committed
Fix persisted direct stores
1 parent 8c26b53 commit 52f959e

2 files changed

Lines changed: 25 additions & 1 deletion

File tree

packages/alpinejs/src/store.js

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,12 @@ export function store(name, value) {
1313

1414
stores[name] = value
1515

16-
initInterceptors(stores[name])
16+
// Initialize the interceptor directly when it is the store value itself.
17+
if (typeof value === 'object' && value !== null && value._x_interceptor) {
18+
stores[name] = value.initialize(stores, name, name)
19+
} else {
20+
initInterceptors(stores[name])
21+
}
1722

1823
if (typeof value === 'object' && value !== null && value.hasOwnProperty('init') && typeof value.init === 'function') {
1924
stores[name].init()

tests/cypress/integration/plugins/persist.spec.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -227,6 +227,25 @@ test('can persist using global Alpine.$persist within Alpine.store',
227227
},
228228
)
229229

230+
test('can persist a primitive as a direct Alpine store',
231+
[html`
232+
<div x-data>
233+
<button @click="$store.language = $store.language === 'EN' ? 'IT' : 'EN'"></button>
234+
<span x-text="$store.language"></span>
235+
</div>
236+
`, `
237+
Alpine.store('language', Alpine.$persist('EN').as('direct-store-language'))
238+
`],
239+
({ get, window }, reload) => {
240+
get('span').should(haveText('EN'))
241+
get('button').click()
242+
get('span').should(haveText('IT'))
243+
window().its('localStorage.direct-store-language').should(beEqualTo(JSON.stringify('IT')))
244+
reload()
245+
get('span').should(haveText('IT'))
246+
},
247+
)
248+
230249
test('persist in Stores is available in init call',
231250
[html`
232251
<div x-data>

0 commit comments

Comments
 (0)