PlasmoHQ / plasmo

🧩 The Browser Extension Framework
https://www.plasmo.com
MIT License
10.03k stars 346 forks source link

[BUG] useStorage not persistent #874

Open Lukkyz opened 7 months ago

Lukkyz commented 7 months ago

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

Code of Conduct

martenmatrix commented 7 months ago

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.

Lukkyz commented 7 months ago

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.

Lukkyz commented 7 months ago

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 : Screenshot

karthest commented 6 months ago
image

maybe because of this

osarhan commented 5 months ago

I am experiencing the same problem. However im dealing with the popup.tsx and not the content scripts.