Pinia getter does not update
Asked Answered
A

2

11

I have following code

<script lang="ts">
import { RouterView } from "vue-router";
import defaultLayout from "@/layouts/default.vue";
import dashboardLayout from "@/layouts/dashboard.vue";
import { useDefaultStore } from "@/stores/default";
import "./index.css";
import { defineComponent } from "vue";
export default defineComponent({
  setup() {
    let { getLayout } = useDefaultStore();

    return { getLayout };
  },
  components: { defaultLayout, dashboardLayout },
});
</script>

<template>
  {{ getLayout }}
  <component :is="getLayout">
    <RouterView />
  </component>
</template>

When i got to /dashboard my state gets updated but the getter does not for some reason, why is that?

<script setup lang="ts">
import { useDefaultStore } from "@/stores/default";
let { getUserData, SET_LAYOUT, getLayout } = useDefaultStore();
SET_LAYOUT("dashboardLayout");
</script>

Here my store:

actions: {
    SET_LAYOUT(layout: any) {
      console.log("setting layout");
      console.log(layout);
      this.layout = layout;
    },
}

I literally can see the changes inside the console but they does not get applied on the UI

Avignon answered 2/3, 2022 at 13:36 Comment(0)
A
24

I have found it out.

You cannot destructure your store, it loses its reactivity

let { getLayout } = useDefaultStore();

So i changed it to

let store = useDefaultStore();

and used store.getLayout and it works!

Avignon answered 2/3, 2022 at 13:39 Comment(2)
Thanks! I tripped up on this same issue! I assumed to maintain reactivity only the state needed storeToRefs to when destructuring the store. However, both state and getters need it. Actions work fine without it though.Copolymerize
This is one way to handle it. Another way is pointed out by Estus Flask's comment that lets you use destructuring while maintaining reactivityPersist
K
12

This is covered by the documentation, this is the case for storeToRefs helper:

const { getLayout } = storeToRefs(useDefaultStore());
Keffiyeh answered 2/3, 2022 at 17:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.