Is it sensible to merge values from localStorage right in the state() method? #821
-
Something like this basically: export const useStore = defineStore('store', {
state() {
const def = {
someVal: 2,
anotherVal: {}
};
if (localStorage.getItem('store')) {
Object.assign(def, JSON.parse(localStorage.getItem('store')));
}
return def;
}
}); Any potential issues here? While I'm here, any reason not to use and subscribe to the store right after its definition, for localStorage forwarding? Something like this right after defining the store: const store = useStore();
store.$subscribe((mutation, state) => localStorage.setItem('store', JSON.stringify(state))); |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments
-
Just trying to make sure I'm not setting myself up for a future headache here... @posva? |
Beta Was this translation helpful? Give feedback.
-
I would say that, in general, merging everything from a localstorage value to the state will be more trouble than benefit. I recommend you to instead use https://vueuse.org/core/uselocalstorage/#uselocalstorage: defineStore('id', {
state: () => ({
someSavedVariable: useLocalStorage(key, initialValue)
// other
})
})
// setup store
defineStore('id', () => {
const someSavedVariable = useLocalStorage(...)
// ...
}) I would recommend you to share more about why you need to use local storage and people will more likely to be able to help you on this one 🙂 |
Beta Was this translation helpful? Give feedback.
I would say that, in general, merging everything from a localstorage value to the state will be more trouble than benefit. I recommend you to instead use https://vueuse.org/core/uselocalstorage/#uselocalstorage:
I would recommend you to share more about why you need to use local storage and people will more likely to be able to help you on this one 🙂
The Discord chat should also be a nice place to ask this kind of question as it might go a bit beyond pinia itself