atomWithStorage subscribe doesn't allow undefined as a return type #3054
-
Bug DescriptionWhen providing a custom https://jotai.org/docs/utilities/storage#validating-stored-values In addition, while undefined makes sense to return when there's no cleanup to do, this example in the documentation should probably return a cleanup function to remove the storage event listener. e.g. import { atomWithStorage } from 'jotai/utils'
import { z } from 'zod'
const myNumberSchema = z.number().int().nonnegative()
const storedNumberAtom = atomWithStorage('my-number', 0, {
getItem(key, initialValue) {
const storedValue = localStorage.getItem(key)
try {
return myNumberSchema.parse(JSON.parse(storedValue ?? ''))
} catch {
return initialValue
}
},
setItem(key, value) {
localStorage.setItem(key, JSON.stringify(value))
},
removeItem(key) {
localStorage.removeItem(key)
},
subscribe(key, callback, initialValue) {
if (
typeof window === 'undefined' ||
typeof window.addEventListener === 'undefined'
) {
return
}
const handler = (e: StorageEvent) => {
if (e.storageArea === localStorage && e.key === key) {
let newValue
try {
newValue = myNumberSchema.parse(JSON.parse(e.newValue ?? ''))
} catch {
newValue = initialValue
}
callback(newValue)
}
}
window.addEventListener('storage', handler)
return () => window.removeEventListener('storage', handler);
},
}) Reproduction Link |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
I've created PRs to address these separately. #3055 to fix the return typing |
Beta Was this translation helpful? Give feedback.
I've created PRs to address these separately.
#3055 to fix the return typing
#3056 to update the docs to return a cleanup function for the storage subscriber