plasmo icon indicating copy to clipboard operation
plasmo copied to clipboard

[BUG] useStorage not persistent

Open Lukkyz opened this issue 1 year ago • 5 comments

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.

Lukkyz avatar Jan 21 '24 03:01 Lukkyz

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.

martenmatrix avatar Jan 21 '24 09:01 martenmatrix

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 avatar Jan 21 '24 17:01 Lukkyz

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

Lukkyz avatar Jan 21 '24 18:01 Lukkyz

image maybe because of this

karthest avatar Feb 21 '24 12:02 karthest

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

osarhan avatar Mar 06 '24 18:03 osarhan