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

useStorage serializer 'read' does not work when the value can be parsed as a number. #3895

Open
7 tasks done
green-mike opened this issue Mar 29, 2024 · 0 comments
Open
7 tasks done

Comments

@green-mike
Copy link

Describe the bug

When the storage stores '100' (as a string), upon reloading the page, the retrieved value from storage becomes 100 (as a number).

In the context of Nuxt SSR, using useStorage along with ssrHandler stores data in cookies. However, when the stored data is a number, accessing it through "storage!.getItem(key)" automatically converts it to a number, whereas the required data type is a string.

Although StorageSerializers.string has been configured for conversion, inspecting the source code reveals that when the type is not a string, serializers.read is not executed, resulting in a type error in the end.

value is number already.

function read(event?: StorageEventLike) {
const rawValue = event
? event.newValue
: storage!.getItem(key)
if (rawValue == null) {
if (writeDefaults && rawInit != null)
storage!.setItem(key, serializer.write(rawInit))
return rawInit
}
else if (!event && mergeDefaults) {
const value = serializer.read(rawValue)
if (typeof mergeDefaults === 'function')
return mergeDefaults(value, rawInit)
else if (type === 'object' && !Array.isArray(value))
return { ...rawInit as any, ...value }
return value
}
else if (typeof rawValue !== 'string') {
return rawValue
}
else {
return serializer.read(rawValue)
}
}

else if (typeof rawValue !== 'string') {

getItem is number

setSSRHandler('getDefaultStorage', () => {
const cookieMap = new Map()
const get = (key) => {
if (!cookieMap.get(key))
cookieMap.set(key, useCookie(key, { maxAge: 2147483646 }))
return cookieMap.get(key)
}
return {
getItem: key => get(key).value,
setItem: (key, value) => get(key).value = value,
removeItem: key => get(key).value = undefined,
}
})

Reproduction

https://stackblitz.com/edit/github-rwbaw3?file=app.vue

System Info

Because the issue with cookies cannot be reproduced on StackBlitz. You can download it and run it locally to see the situation.

Used Package Manager

npm

Validations

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant