Assigning initial values within the created() method using Vuex

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.

Answer №1

Discovered the issue - failed to retrieve the value of navigator.language in my getter function

Answer №2

Encountered issues in the given example:

  • The function defaultLang is not returning
  • Accessing store without using this.$store in component

Check out an example in action: https://codepen.io/ptcmariano/pen/jQZmWW

const mapGetters = Vuex.mapGetters;
const mapActions = Vuex.mapActions;
const mapState = Vuex.mapState;

const store = new Vuex.Store({
    state: {
          userData: {
            prefLang: "UNDEF"
            // other data..
          }
    },
    getters: {
        defaultLang: () => { return navigator.language.slice(0,2) }
    },
    actions: {
        setDefaultLang({ state, getters }) {
            state.userData.prefLang = getters.defaultLang
        }
    }
});


new Vue({
    el: "#app",
    store: store,
    template: `<div class="chat-display"> <p> lang: {{ this.userData.prefLang }}</p> </div>`,
    created() {
        this.$store.dispatch('setDefaultLang')
    },
    computed: {
        ...mapGetters([
            'defaultLang'
        ]),
        ...mapState([
            'userData'
        ])
    },
    methods: {
        ...mapActions([
            'setDefaultLang'
        ])
    }
});
#app

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way for CasperJS to access the underlying PhantomJS objects and references?

Currently, I am in the process of transitioning a script from PhantomJS to CasperJS, and I am curious if Casper offers any references to the Phantom objects it utilizes internally. It is important to note that Phantom provides certain functionalities that ...

Exploring the power of parent-child functions in Ajax promises

Trying to validate tag input against a database using an ajax call with taggle.js. The taggle documentation states to use return false on the onBeforeTagAdd event in order to prevent a tag from being added. However, due to the asynchronous nature of ajax ...

Struggling with the performance of my JavaScript canvas map script

Below is the script I've written for a prototype that utilizes 128x128 tiles to create a map on a canvas that can be dragged around by the user. The script is functioning, but I'm facing some challenges: 1. Poor performance that needs to be addr ...

"Converting an image in Byte[] format to a Base64 string in JavaScript: A step-by-step

Can anyone help me figure out how to convert an image from an SQL database into a Base64 string? The image is currently in the format {byte[6317]}. ...

What is the best way to retrieve the component object of the child components I am rendering in a list?

Within my component, I have a JSON payload containing a service. However, I am unsure of the best way to access the list items component objects from the parent component. ...

How can I create an onclick link within an alert message using JavaScript, even when the alert is not consistently displayed?

I am facing an issue with an alert that is supposed to appear under specific conditions on my website. The alert includes a link that should trigger some code when clicked. However, I keep getting an error message saying "ReferenceError: doTheThing is not ...

Opting to monitor element visibility over relying solely on page load with Neustar WPM

I need help with writing a Neustar WPM script to time the button click until an overlay appears. Here is what my current script looks like: var webDriver = test.openBrowser(); var selenium = webDriver.getSelenium(); webDriver.get('https://www. ...

My mongoose sort function doesn't seem to be functioning properly. What could be the issue?

Hey there! I've got a simple API up and running on Node.js, using MongoDB as my database with Mongoose for querying. The issue I'm facing is related to sorting data using the mongoose 'sort' method. Instead of behaving as expected, it s ...

Retrieving information from an API and showcasing the resulting data in a data grid

An issue arose while attempting to retrieve data from an API and passing it to a DataGrid component. Here is an example of the data returned: { data: [{ type: 'PropertyDamage', id: '100', attributes: { ident ...

Finding the specific index of an element in the code has proven challenging, as it consistently returns a value of -1

const index = this.List.findIndex((item:any) => { return item.NAME === result.NAME; }); The index is consistently returning -1 even when the element is found in the List. ...

invoking JavaScript code from C#

Is it possible to use JavaScript functions to show and hide an element on a webpage by calling them from within a C# method? UPDATE: I attempted to use RegisterStartupScript (shown below) but unfortunately, it did not successfully hide the elements as int ...

Tips for utilizing New FormData() to convert Array data from an Object for executing the POST request with Axios in ReactJs

When working on the backend, I utilize multer to handle multiple file/image uploads successfully with Postman. However, when trying to implement this in ReactJS on the frontend, I find myself puzzled. Here's a sample case: state = { name: 'pro ...

Using a loop in a Vue.js slick slider: easy step-by-step guide

While utilizing vue-slick link https://www.npmjs.com/package/vue-slick within a bootstrap modal, I encountered an issue when using a v-for loop to iterate through the items. The problem can be seen in this example: https://i.sstatic.net/PhJCE.jpg. Below i ...

Issues encountered with VueJS Bootstrap implementation include failure to load app.scss properly as well as problems with the dismissable b-alert button displaying as a square with an "x" in the center

I am facing some difficulties while incorporating Bootstrap into my Vue.js project for the first time. Following the instructions provided here, I added everything step by step until I reached the point where I had to create app.scss. Placing it in the as ...

eliminate the firebase firestore query using onSnapshot

Seeking assistance with the following code snippet: firebase.firestore() .collection("chatrooms") .doc(`${chatId}`) .collection(`${chatId}`) .orderBy("timestamp") .limit(50).onSnapshot((snapshot) => { //performing oper ...

Personalize dat.gui using various documents

Recently, I delved into using the dat.GUI API alongside Three.js and found myself contemplating the best method to personalize the GUI across various files. My goal is to incorporate new Controllers into a single GUI instance from different files, each fil ...

Stop GIF files from refreshing when utilized by a different component in a react application

I am facing an issue with two components, let's call them componentA and componentB. Both components are importing a .gif file named image.gif. The problem is that image.gif does not loop, so it should only play once unless it gets updated. Initially ...

Getting the true height without needing jQuery

let element = document.getElementById('test'); console.log(element.scrollHeight); <div style="height: 30px;" id="test"> <p>ffffffffff</p> <p>gggggggggg</p> ...

How can I effectively implement a withAuth higher order component (HOC) in TypeScript within Next.js?

Currently, I am working on a Next.js application and implementing the next-auth package. My goal is to develop a Higher Order Component (HOC) that can determine if the component has an active session or not. Along with this, I am utilizing eslint for code ...

What could be causing the lack of authentication for the user following Google authorization in nuxt-auth-next?

Here's the configuration I'm using for nuxt-auth-next in my Nuxt application: nuxt.config.js auth: { strategies:{ google: { clientId: "my_client_id.apps.googleusercontent.com", redirectUri: `http://localhost:3000/apps`, ...