|
Hi, I'm trying to figure out the best way to share state between islands. I saw this discussion (#61) but I'm unsure exactly how to use Pinia in this case. Specifically, I don't understand where I initialise a Pinia store and how I use it within different islands. My setup is pretty simple. I have two islands. One island fetches some data from a server via a rest API and I'd like to make that state available to another dynamically loaded component on the same page. As far as I can make out, I have to call /// useSharedState.ts
export default function useSharedState() {
const pinia = createPinia();
const useStore = defineStore("pinia", () => {
const stuff: Ref<string | undefined> = ref(undefined);
return { stuff };
});
return { pinia, useStore };
}/// Component A
<script lang="ts" setup>
import useSaleor from "@/hooks/useSharedSate";
const { useStore, pinia } = useSharedState();
const store = useStore(pinia);
await fetchSomeState()
.then((stuff) => (store.stuff= stuff))
.catch((err) => console.error(err));
</script>/// Component B
<script lang="ts" setup>
import useSaleor from "@/hooks/useSharedSate";
const { useStore, pinia } = useSharedState();
const store = useStore(pinia);
// do things with store.stuff
</script> |
Replies: 2 comments
|
Hi Oliver! In the implementation above, The store should be defined at the module level, which ensures the same store is imported by both islands: /// useSharedState.ts
const pinia = createPinia()
const useStuffStore = defineStore('stuff', () => {
const stuff: Ref<string | undefined> = ref(undefined)
return { stuff }
})
export function useStuff () {
return useStuffStore(pinia)
}Alternatively, you can simplify this pattern even further, and not use /// useSharedState.ts
const stuff: Ref<string | undefined> = ref(undefined);
export function useStuff () {
return { stuff }
}Vue refs can be use to share state between islands, all you need to do is ensure the ref is created once (like we do in this example in the module scope, instead of inside a function). Let me know how it goes! 😃 |
|
well, that makes things a lot simpler! Thanks @ElMassimo that works a treat! |
Hi Oliver!
In the implementation above,
useSharedState()creates and returns a new store every time is called, so each island is getting a separate store.The store should be defined at the module level, which ensures the same store is imported by both islands:
Alternatively, you can simplify this pattern even further, and not use
piniaat all: