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

fix(useStorage): read object only when it's serialized differently (#2782) #3091

Merged
merged 4 commits into from Aug 25, 2023
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
4 changes: 3 additions & 1 deletion packages/core/useStorage/index.test.ts
@@ -1,5 +1,5 @@
import { debounceFilter, promiseTimeout } from '@vueuse/shared'
import { isVue3, ref } from 'vue-demi'
import { isVue3, ref, toRaw } from 'vue-demi'
import { beforeEach, describe, expect, it, vi } from 'vitest'
import { nextTwoTick, useSetup } from '../../.test'
import { StorageSerializers, customStorageEventName, useStorage } from '.'
Expand Down Expand Up @@ -164,10 +164,12 @@ describe('useStorage', () => {
data: 123,
})

const storeRaw = toRaw(store.value)
store.value.name = 'b'
await nextTwoTick()

expect(storage.setItem).toBeCalledWith(KEY, '{"name":"b","data":123}')
expect(storeRaw).toBe(toRaw(store.value))

store.value.data = 321
await nextTwoTick()
Expand Down
4 changes: 3 additions & 1 deletion packages/core/useStorage/index.ts
Expand Up @@ -254,7 +254,9 @@ export function useStorage<T extends(string | number | boolean | object | null)>

pauseWatch()
try {
data.value = read(event)
const newData = read(event)
if (typeof newData !== 'object' || serializer.write(newData) !== serializer.write(data.value))
data.value = read(event)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This doesn't seem to be very efficient. We better:

  • Compare raw data with the serialized data.value (one serialization)
  • And read the event when they are not equal (one parsing)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

thanks

}
catch (e) {
onError(e)
Expand Down