JoeBayLD
JoeBayLD

Reputation: 999

Using dynamic Pinia stores when Vue route changes

I have an app that has a handful of dynamic components and each one needs it's own store. I'm having anm issue referencing the correct Pinia store when each route changes. The store id is based off the current route. See code below.

This is the component that creates / uses the store.

<script setup lang="ts">
import makeStore from "./store";
import { useRoute } from "vue-router";

const route = useRoute();
const id = route.params.widgetID;

const store = makeStore(id);

// now i use the store in my template
</script>

This code creates a new store with the given id:

import { defineStore } from "pinia";
import { ref } from "vue";

export default function makeStore(id: string) {
  return defineStore(id, () => {
    const testString = ref("");
    return { testString };
  })();
}

The issue is when I have the route update, the store doesn't because it's originally created with the first components params. Is there a better way to do this?

Upvotes: 0

Views: 1394

Answers (1)

HappiSmyle
HappiSmyle

Reputation: 111

I would suggest you to use onBeforeRouteUpdate to initialize correct store

let store = makeStore(route.meta.widgetId ?? 'default');
onBeforeRouteUpdate((to) => {
  store = makeStore(to.meta.widgetId);
});

I assume that your component code is base route component. When you navigate to child routes - Vue does not re-render base component if no dependency was updated. Same goes if 2 separate routes will use same component.

I did setup complete playground. You can put some text in input, then switch between routes to verify that input value persists based on widgetId

Upvotes: 0

Related Questions