plasmo
plasmo copied to clipboard
[BUG] useStorage not persistent
What happened?
useStorage is not persistent when refreshing a page. Here's my content.tsx :
const Content = () => {
const [hello, setHello] = useStorage("hello", (v) => {
return v === undefined ? {} : v
})
useEffect(() => {
console.log(hello)
const random = Math.floor(Math.random() * 50)
setHello({ ...hello, [random]: "test" })
}, [])
return <button>OK</button>
}
export default Content
console.log give undefined
Version
Latest
What OS are you seeing the problem on?
Linux
What browsers are you seeing the problem on?
Chrome
Relevant log output
No response
(OPTIONAL) Contribution
- [x] I would like to fix this BUG via a PR
Code of Conduct
- [X] I agree to follow this project's Code of Conduct
- [X] I checked the current issues for duplicate problems.
Describe your issue next time more clearly. It is hard to help you this way. I can only guess, but I believe using:
setHello((prevState) => ({ ...prevState, [random]: "test" }))
will fix your issue.
Sorry, I will try to explain it better. When a page is loaded I want to add a key in the object "hello" on the storage. But the console.log(hello) in useEffect is always undefined (so it is not persistant otherwise it will contains the key added from the last loaded page). If I reload a page three time I expect it to contain 3 random key. I tried this :
setHello(prevState => {
console.log(prevState) // => undefined;
setHello({...prevState, [random]: "test"})
})
But it is the same.
For more clarity :
const Content = () => {
const [hello, setHello] = useStorage("hello", (v) => {
console.log("A", v)
return v === undefined ? {} : v
})
useEffect(() => {
setHello((prevState) => {
console.log("B", prevState)
const random = Math.floor(Math.random() * 50)
return { ...prevState, [random]: "test" }
})
console.log("C", hello)
}, [])
return <p>Hello</p>
}
Result when loading a page :
I am experiencing the same problem. However im dealing with the popup.tsx and not the content scripts.