Plugin function is executed every time useStore() is called? #678
-
I am trying to write a small plugin to keep data in localStorage in sync with Pinia store. The idea is to listen to changes via The problem is that the function returned by the plugin is called each time there is a Let's take a look at the code to convey my idea: // piniaPersistence.js
export default function piniaPersistence() {
return ({ options, store }) => {
const restoreData = () => {
console.log('restoreData is called')
// READ
localStorage.getItem(... )
store.$patch( ... )
}
if (options.persistence) restoreData()
store.$subscribe((mutation, state) => {
// WRITE
localStorage.setItem( ... )
}
}
} // main.js
import piniaPersistence from 'piniaPersistence'
const app = createApp(App)
const pinia = createPinia()
pinia.use(piniaPersistence())
app.use(pinia)
// from here onwards,
useStore() // <-- each time this happens, restoreData() is called |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 1 reply
-
This is normal for v1 and was even explained in docs. It shouldn't happen in v2 tho 🙂 |
Beta Was this translation helpful? Give feedback.
-
Thanks @posva for the reply. I love your work. In the plugin function itself when there is a This leads to infinity loop. |
Beta Was this translation helpful? Give feedback.
Thanks @posva for the reply. I love your work.
I am using version
^2.0.0-rc.6
.In the plugin function itself when there is a
useStore()
call, the function would execute again,probably because Pinia did not register the plugin yet due to the first call is not finished yet.
This leads to infinity loop.
My situation is very very niche, and fortunately the workaround is very simple, I added a flag check at the top of the function.