Trouble with Vue 3 watch not persisting after page refresh

Attempting to create a Vue application that supports two languages, utilizing local storage and store to store the selected language.

Initially, everything appears to be functioning correctly. After the user logs in, the default language is displayed in both components. Clicking on the second language triggers watchers in both components, updating the text accordingly. However, upon refreshing the page and selecting another language, only the navbar component switches languages, while the home component fails to update. Despite logging the chosen language in the setter, the watcher in the home component does not activate. The issue persists even after logging out, refreshing, and starting anew.

Store:

const localLanguage = localStorage.getItem('xx-user-language')

const state = () => ({
  userLanguage: undefined,
});

const getters = {
  getUserLanguage(state) {
    if(localLanguage !== null && localLanguage !== undefined){
        return localLanguage
    }
    return state.userLanguage;
  },
};


const mutations = {
  setUserLanguage(state, data) {
    localStorage.setItem('xx-user-language', data)
    console.log("setter " + data)
    state.userLanguage = data;
  },
};

Navbar Component:

HTML:

   <div title="deutsch" class="icon-container">
              <img @click="setLanguage('de')" src="german.png" alt="deutsch">
            </div>
            <div title="english" class="icon-container">
              <img @click="setLanguage('en')" src=".english.png" alt="english">
            </div>

JS:

computed:{
    ...mapGetters('language',{
      getUserLanguage:"getUserLanguage"
    })
  },
  watch:{
    getUserLanguage: function(newValue){
      this.setLanguage(newValue)
    }
  },

 methods: {
    setLanguage(lang){
        this.setUserLanguage(lang)
        this.text = text.navbar[lang]
    },
    ...mapMutations('language',{
      setUserLanguage:"setUserLanguage"
    })
  }

Home Component: JS:


 computed: {
    ...mapGetters('language',{
      getUserLanguage:"getUserLanguage"
    })
  },
  watch: {
    getUserLanguage: function(newValue){
      console.log("home watcher" + newValue)
      this.setLanguage(newValue)
    }
  },
  methods: {
    setLanguage(lang){
        this.text = text.homepage[lang]
    },
  },

Answer №1

The correct structure for your Vuex getter should be:

const state = () => ({
  userLanguage: localStorage.getItem('xx-user-language'),
});

const getters = {
  getUserLanguage(state) {
    return state.userLanguage;
  },
};

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

A guide on using Material UI - InputLabel in JavaScript

I'm currently integrating a form from this Codepen link into my project built with Codeigniter. However, I am encountering issues after incorporating material-ui into the CodeIgniter framework. The problems I am facing include an invalid token and an ...

An error has occurred in nodejs: headers cannot be set after they have already been sent

I'm a newcomer to Node.js and encountering some challenges. Whenever I attempt to open 127.0.0.1:3000/bejelentkezes, I encounter the following error: POST /bejelentkezes 500 550.784 ms - 2259 GET /css/404.css 304 2.751 ms - - 1 Successful login Erro ...

Undefined values in Javascript arrays

Currently, I am sending a JSON object back to a JavaScript array. The data in the array is correct (I verified this using Firebug's console.debug() feature), but when I try to access the data within the array, it shows as undefined. Below is the func ...

Begin the React counter with a starting value of two

Recently, I set up a new React application using the create-react-app command and ran a test with a render counter. Here is the code snippet: import React, { useState } from "react"; let render = 0; export default function App() { const [cou ...

Obtain value of dropdown selection upon change

What is the best way to retrieve the selected value in a drop-down menu when the ID dynamically changes with each refresh? Is it possible to access the particular selected value even when the ID changes? <select name="status" id="dropdown_status3352815 ...

Can JavaScript be used to dynamically update drop down lists in a gridview?

My gridview has multiple fields including PreviousPoints, GainedPoints, and TotalPoints. In edit mode, PreviousPoints is not editable, GainedPoints is a dropdown list, and TotalPoints is also a dropdown list. Whenever the selected value in GainedPoints ch ...

The Material UI button feature neglects to account for custom CSS styles when attempting to override the default settings

Utilizing a custom bootstrap css styles in my react app, I am seeking to enhance the default material ui components with the bootstrap styles. import React, {useState} from 'react'; import 'cg-bootstrap/core/build/cg-bootstrap-standard.css&a ...

Assigning names to the points on the AxisHelper component in THREE.js

Take a look at the code snippet provided below: <html> <head> <title>My first Three.js app</title> <style>canvas { width: 100%; height: 100% }</style> </head> <body ...

What does the JS Array Filter function return?

Is it necessary to include a return statement in the filter function when NOT using ES6 arrow syntax? Could the two separate filter functions be combined into one for efficiency? cars.filter(function(car, index) { return car[0].setAttribute("data-ori ...

Parsing Problem---Is there a Parsing Error?

My code includes a function that calculates the total of cells and then displays it in a textbox: function UpdateTotal() { var total = parseFloat('0.0'); $("#<%= gvParts.ClientID %>").find("tr").not(".tblResultsHeader").each(funct ...

Extension ConfirmButtonExtender

There is a scenario where I need to skip the ConfirmButtonExtender based on the value of another field in the page. Typically, when a user clicks on my "Cancel" button, a modal popup appears using the confirmbuttonextender and the modalpopupextender. The ...

The submission of the form proceeds even with the warning displayed

I am facing an issue with a form that consists of one text field and a submit button. The user is required to input a 3-digit number, and if the number is greater than 200, a warning should be displayed. If the user clicks OK, the form should be submitted. ...

What could be causing the error "Err: user.validPassword is not a function" to occur

I am in the process of developing a node.js app and I have implemented Passport js. After referring to the Passport-local documentation on their official website, I decided to utilize the local passport-strategy. However, I encountered an error stating tha ...

Maintain the current application state within a modal until the subsequent click using Jquery

Due to the challenges faced with drag and drop functionality on slow mobile devices, I am considering implementing a modal approach for moving elements from one place to another. Here is how it would work: When a user clicks on an item, it is visually ma ...

What are the distinct roles of the server and client in a Nuxt SSR application?

Currently, I am working with Nuxt 2.13 and developing an e-commerce platform. However, I have encountered some server resource issues where the initial site load is taking longer than expected (although route changes are fast and smooth). I am curious to ...

Understand which form has been submitted

I have eight Forms in a page (Form0, Form1, Form2 and so forth). Each form, when submitted, sends data to ReassignPreg.php using JavaScript, which then searches for the data in the database and returns it as JSON. The corresponding divs on the page are the ...

The loading feature fails to activate when attempting to execute a function

I recently encountered an issue with my loading effect code implementation. It appears that the loading effect does not work when I click the button, but it works perfectly fine without the function running. The function seems to interfere with the loadi ...

store JSON data within an HTML list element

I've been working on a JavaScript script that allows me to generate list items in HTML. Right now, I have functionality to drag and remove the items using another script. However, I am interested in adding some additional information to each list item ...

Changing the style of opening curly braces in JavaScript code styling

I have a piece of JavaScript code written for Vue that I would like to discuss. It is common practice in the JavaScript world to place the opening curly brace at the end of a line of code. <script> export default { name: 'newUser', data ...

The use of a <button> element in a React App within a Web Component with Shadow DOM in Chrome disables the ability to highlight text

An unusual problem has arisen, but I have a concise example that demonstrates the issue: https://codesandbox.io/s/falling-architecture-hvrsd?file=/src/index.js https://i.stack.imgur.com/CkL4g.png https://i.stack.imgur.com/nDjuD.png By utilizing the divs ...