I have a scenario where I need to set a default value for a state property when a component is initialized. Specifically, I want the user's preferred language prefLang
to be derived from navigator.language
if they haven't specified it through user input.
Currently, my implementation is not producing the desired result after migrating to Vuex. While I'm not encountering any errors, the default value assigned to prefLang
, which is UNDEF
, is displayed instead of the value extracted from navigator.language.
This leads me to ask: How can I initialize a state property with a default value in the absence of user input?
Below is a simplified version of the code snippet I am dealing with:
store.js
const state = {
userData: {
prefLang: "UNDEF"
// other data..
}
}
const getters = {
defaultLang: () => { navigator.language.slice(0,2) }
}
const actions = {
setDefaultLang({ state, getters }) {
state.userData.prefLang = getters.defaultLang
}
}
Chat.vue
<template>
<div class="chat-display">
<p>{{ this.userData.prefLang }}</p>
</div>
</template>
<script>
import { mapGetters, mapActions, mapState } from 'vuex'
export default {
name: 'chat-display',
created() {
this.store.dispatch('setDefaultLang')
},
computed: {
...mapGetters([
'defaultLang'
]),
...mapState([
'userData'
])
},
methods: {
...mapActions([
'setDefaultLang'
])
}
</script>
Any help on this matter would be greatly appreciated.