I am using pinia in a vue 3 project. The store has a few variables in the state, but when I try to set these variables in a method a have in the actions, only the first variable seems to update while the rest remain unchanged. also good to mention that I am using Local storage inside the pinia store to ensure that the values persist on page refresh. I also have another store that is pretty much identical to the one I have pasted below but doesnt have the same issue.
pinia store:
import { defineStore } from 'pinia'
import { useLocalStorage } from "@vueuse/core"
export const useExpertStore = defineStore('Expert', {
state: () => {
return {
name: useLocalStorage('name'),
about_me: useLocalStorage('about_me'),
ExpertEmail: useLocalStorage('ExpertEmail'),
Experience: useLocalStorage('Experience'),
field: useLocalStorage('field'),
profile_picture: useLocalStorage('profile_picture'),
rate: useLocalStorage('rate'),
rating: useLocalStorage('rating'),
};
},
getters: {
getName: (state) => state.name ,
getAboutMe: (state) => state.about_me ,
getExpertEmail: (state) => state.ExpertEmail ,
getExperience: (state) => state.Experience ,
getField: (state) => state.field,
getProfile_picture: (state) => state.profile_picture,
getRate: (state) => state.rate ,
getRating: (state) => state.rating ,
},
actions: {
setExpert(name,about_me, email,Experience,field, profile_picture,rate,rating) {
this.name = name
this.about_me = about_me
this.ExpertEmail = email
this.Experience = Experience
this.field = field
this.profile_picture = profile_picture
this.rate = rate
this.rating = rating
},
},
});
Calling the store and settings the values:
const ExpertStore = useExpertStore()
ExpertStore.setExpert(props.Expert.name,props.Expert.about_me,props.Expert.email,props.Expert.experience,props.Expert.field,props.Expert.profile_picture,props.Expert.rate,props.Expert.rating)
getting the values from the store:
const ExpertStore = useExpertStore()
console.log(ExpertStore.Experience)
When getting the values from the store after setting them, only the name is set while all the other values are undefined
2
Answers
I am not sure why your code is only setting the name (debugging or Vue tools can give lots of insights). But if you want to persist the store, you’d better use https://prazdevs.github.io/pinia-plugin-persistedstate/guide/config.html. That way you don’t have to deal with useLocalStore(), which might also be throwing off your pinia instance.
First of all you will want to use the
storeToRefs()
.const { Experience } = storeToRefs(ExpertStore)