Reputation:
import { defineStore, acceptHMRUpdate } from 'pinia';
import { v4 as uuidv4 } from 'uuid';
export const useStoreNotes = defineStore('storeNotes', {
state: () => ({
notes: [
{
id: '8d3ce756-ef35-4e68-80bd-fb97e03a831b',
content: 'Learn React',
},
{
id: '11860d36-cb57-455e-9b9c-083ef5762f7e',
content: 'Learn Java',
},
],
}),
})
if (import.meta.hot) {
import.meta.hot.accept(acceptHMRUpdate(useStoreNotes, import.meta.hot));
}
Hey, I'm trying to use the HMR (Hot Module Replacement) in Pinia (Vuex5). I'm also using Vite. I tried to use the HOT reloading from the official documentation of Pinia: https://pinia.vuejs.org/cookbook/hot-module-replacement.html
But the hot reloading isn't working. I have to refresh the page if I update something in the store, and I want to see the changes without refreshing the page.
Upvotes: 4
Views: 5954
Reputation: 1889
I had the same problem only to later learn that I was using the store wrongly. This is how it must be used within your component.
<template>
<pre>{{ notesStore.length }}</pre>
</template>
<script setup>
import { useStoreNotes } from "../stores/useStoreNotes";
const notesStore = useStoreNotes();
</script>
Upvotes: 0
Reputation: 41
It looks like you have the correct syntax. My guess is that, like me, you expected the page to update when you change the state values; however it appears HMR is actually working as intended. See the answer to this issue:
Yes, the idea is that adding new state should not reset the other values of the state so existing state values are always preserved. This also means that you can change a value, comment the line and save (this removes the state property) then un comment and save again.
I was able to recognize that the HMR was indeed working by pulling up the terminal noting that my update to the store was logged. See example of my terminal.
Likewise, if you add new state to the store, then you should see the store update accordingly in the Vue DevTools. These two ways were how I was able to identify that HMR was working as intended (though not how I had hoped unfortunately).
Finally, as mentioned in the response to the above GitHub issue, you can indeed comment out the state code, save, uncomment, and then save again to force the new value to appear. Not ideal in my opinion, but I suppose it is a feasible workaround.
Upvotes: 4