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

Add modifier defer to control deferring storage #3463

Closed
wants to merge 5 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions packages/persist/src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ export default function (Alpine) {
let persist = () => {
let alias
let storage = localStorage
let defer = false
let isInitial = true

return Alpine.interceptor((initialValue, getter, setter, path, key) => {
let lookup = alias || `_x_${path}`
Expand All @@ -15,15 +17,18 @@ export default function (Alpine) {
Alpine.effect(() => {
let value = getter()

storageSet(lookup, value, storage)
if (!defer || !isInitial) storageSet(lookup, value, storage)

setter(value)

isInitial = false
})

return initial
}, func => {
func.as = key => { alias = key; return func },
func.using = target => { storage = target; return func }
func.using = target => { storage = target; return func },
func.defer = target => { defer = true; return func }
})
}

Expand Down
34 changes: 34 additions & 0 deletions tests/cypress/integration/plugins/persist.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,23 @@ test('can persist string',
},
)

test('can defer persisting a string',
[html`
<div x-data="{ message: $persist('foo').defer() }">
<input x-model="message">

<span x-text="message"></span>
</div>
`],
({ get }, reload) => {
get('span').should(haveText('foo'))
get('input').clear().type('bar')
get('span').should(haveText('bar'))
reload()
get('span').should(haveText('bar'))
},
)

test('can persist array',
[html`
<div x-data="{ things: $persist(['foo', 'bar']) }">
Expand All @@ -50,6 +67,23 @@ test('can persist array',
},
)

test('can defer persisting an array',
[html`
<div x-data="{ things: $persist(['foo', 'bar']).defer() }">
<button @click="things.push('baz')"></button>

<span x-text="things.join('-')"></span>
</div>
`],
({ get }, reload) => {
get('span').should(haveText('foo-bar'))
get('button').click()
get('span').should(haveText('foo-bar-baz'))
reload()
get('span').should(haveText('foo-bar-baz'))
},
)

test('can persist object',
[html`
<div x-data="{ something: $persist({foo: 'bar'}) }">
Expand Down