0👍
You will need to destructure your store with storeToRefs
which will maintain the reactivity of the state, meaning your UI will rerender on state change.
import { storeToRefs } from "pinia";
const store = useUserStore();
const { data: user, token } = storeToRefs(store); // destructures "data" from store to new variable "user"
0👍
Use ref explicitly can help Vue’s reactivity system work more predictably. Modify your store like this:
import { defineStore } from "pinia";
import { ref } from "vue";
export const useUserStore = defineStore("user", {
state: () => ({
data: ref({}),
token: ref(null),
}),
actions: {
setUser(userData) {
this.data = userData.data;
this.token = userData.token;
},
},
});
Wrap template variables in a computed property. This ensures that the template always reads the reactive data. Change your Vue template script section like this:
<template>
<div>
{{ user }} {{ token }}
<button @click="login">Login</button>
</div>
</template>
<script setup>
import { useUserStore } from "@store";
import { computed } from "vue";
const store = useUserStore();
const user = computed(() => store.data);
const token = computed(() => store.token);
const login = () => {
const userData = {
data: {
name: 'Giorgi',
lastname: 'Shalamberidze',
email: 'gigi@gmail.com'
},
token: 'MY_API_TOKEN'
};
store.setUser(userData);
};
</script>
Source:stackexchange.com