Switching languages in Nuxt i18n causes the data object to reset

Recently, I incorporated nuxt-i18n into a project to support multiple languages. Everything was running smoothly until I encountered an issue where switching language while filling out a form resulted in all data on the page being lost.

To tackle this problem, I created a form and utilized v-model to connect the data with the page's data object.

<div class="form-group">
   <label for="username">{{ $t('form.username') }}</label>
   <input v-model="user.username" type="username" class="form-control" id="username" />
</div>

This represents the page's data object:

data: () => {
  return {
     user: {
       username: ''
    }
}

Upon typing a username in the field, the model gets updated as expected. However, upon changing the language on the page, the data is reset once the new language selection is made.

To change the language, such as clicking on the Dutch flag icon, I utilize the following code snippet:

switchLocalePath(locale.code) // local.code is 'nl' in this case

Whenever there is a language switch, the slug should update correspondingly. The code below illustrates the configurations for the i18n package within my nuxt.config.js file.

modules: [
    ['nuxt-i18n', {
      locales: [
        {
          code: 'en',
          iso: 'en-US',
          name: 'English'
        },
        {
          code: 'nl',
          iso: 'nl-NL',
          name: 'Nederlands'
        }
      ],
      defaultLocale: 'nl',
      parsePages: false,
      pages: {
        'account/register': {
            en: '/account/register',
            nl: '/account/registreren'
        },
        'account/index': {
            en: '/account/login',
            nl: '/account/inloggen'
        }
      },
      vueI18n: {
        fallbackLocale: 'nl',
        messages: { nl, en }
      }
    }],
]

The precise query

Most features are functioning just as intended. However, each time I switch the language, the page's data object seems to be cleared (without a visible page reload). Consequently, when I am in the middle of filling out a form and then alter the language before submission, all entered data is erased.

Is there a way, if possible, to ensure that all data persists even when toggling the language?

Appreciate your insights!

Answer №1

When attempting to switch locales using the method outlined above, I consistently encounter the same issue.

<v-list>
    <v-list-item
        v-for="locale in availableLocales"
        :key="locale.code"
        @click="$router.push(switchLocalePath(locale.code))"
    >
        <v-list-item-title>{{ locale.name }}</v-list-item-title>
    </v-list-item>
</v-list>

I also experimented with $i18n.setLocale(locale.code), only to experience the same result.

Although this may belong as a comment, my current reputation level does not allow for it (requires 50 rep), so I am including it here as part of the problem description.

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

Declare React component as a variable

I'm facing a simple issue that I need to solve. After creating a React app using npx create-react-app, I designed a Map component which I integrated into my view with the following code: class App extends Component { render() { return ( ...

A link is not allowed to be a child of another link

An issue arises in a React.js application Warning: validateDOMNesting(...): <a> cannot be nested under another <a>. Refer to Element > a > ... > a for more information. What is the significance of this warning? How can it be avoided ...

Ensuring Compliance with GDPR through Cookie Consent Logic

Since the introduction of GDPR, I find myself in need of clarity on the steps to take both server-side and client-side to ensure compliance. Apologies for the plethora of questions. I currently have a first-party cookie that is used to store a session coo ...

How can I edit this code in JSPDF to print two pages instead of just one?

Currently, I have a script that can generate a PDF from one DIV, but now I need to create a two-page PDF from two separate DIVs. How can I modify the existing code to achieve this? The first DIV is identified as #pdf-one and the second DIV is #pdf-two. p ...

How to validate a <select> element with parsley.js when it is dynamically populated with an object?

I'm struggling to validate a <select> element in my form. With the help of knockout.js, I select a location which then populates the Service Point based on the Location chosen. However, when I try to validate the form using parsley.js after pres ...

ApolloError: Undefined fragment detected and unable to be used

Within the complex structure of my application, I encounter the following: import { gql } from '@apollo/client'; gql` fragment StuffTable on Stuff { id status } `; export const GetStuffDocument = gql` query GetStuff($id: ID!) { ...

Unable to display image using EJS and Multer

While working on my node.js application, I encountered an issue with rendering the uploaded image file. I have successfully integrated multer to handle file uploads, and the images are being stored in the correct folder. However, when trying to display the ...

Is it possible to utilize the NavigationTimingAPI with asynchronous requests?

Currently, I am working on implementing performance measuring functionality in our project that utilizes custom elements v1. The NavigationTimingAPI provides detailed measurements for various navigation types (navigate, reload, browser back/forward): Is ...

Creating a duplicate or copy of an element in jQuery using

My dilemma involves a div that consists of text/images and a custom jQuery plugin designed for those images. The plugin simply executes a fadeIn/fadeOut effect every 3 seconds using setInterval. This particular div acts as a "cache" div. When a user wants ...

Incorporate a pseudo class to a unique custom template or directive within an Angular project

I have been developing a custom dropdown menu directive in AngularJS. The issue I'm facing is that the buttons in my template become inactive when interacting with the dropdown menu, unlike a regular HTML select which remains active while the dropdown ...

Issue with retrieving data using AngularJS Restangular

I've been trying to figure out how to make restangular work properly. When I call my API (using the endpoint /user) I receive the following JSON response: { "error": false, "response": { "totalcount": 2, "records": [{ "id": "1", ...

Image encoded in base64 not appearing on the screen

Hey there, I'm currently working on implementing a jQuery image uploader that generates a base64 code when an image is selected. function readImage(input) { if (input.files && input.files[0]) { var FR= new FileReader(); FR.onload ...

Exploring the process of integrating absolute paths within a global SCSS file in a VueJS project

The webpack configuration in my vue.config.js file looks like this: const path = require("path"); module.exports = { pluginOptions: { 'style-resources-loader': { preProcessor: 'scss', patterns: [ "./src/style ...

The vue-test-utils setData method is failing to trigger a re-render of the component

Currently, I am utilizing vue-test-utils in conjunction with jest. In my Login Component, I have a router-link being displayed. Additionally, I am passing the router to the component. Within this context, there exists data named 'email', and whe ...

NextJs does not allow external synchronous scripts

I am currently working with Next.js version 11.x Whenever I attempt to add an external script like the example below, I encounter an error when executing the yarn build. <Head> <link rel="stylesheet" type=" ...

Can I send a DELETE request with request body and headers using Axios?

When working with Axios in ReactJS, I am attempting to send a DELETE request to my server. In order to do this, I need to include the following headers: headers: { 'Authorization': ... } The body of the request consists of: var payload = { ...

Utilize a single array to point to multiple elements

I am curious about the potential to create a unique scenario using JavaScript. Imagine having two arrays: a = [1, 2, 3] b = [4, 5, 6] What if we could combine these arrays into a new array, c, that encapsulates both: c = [1, 2, 3, 4, 5, 6] The intrigui ...

What is the designated destination for JWT Tokens?

For my user login/signup process, I'm utilizing JWT and have a query regarding how the token is transmitted. At present, I am saving the token as a property in a JSON object on the server side, then passing it to the front-end. Upon receiving the obj ...

Is there a way to reset the canvas with just a click of a button?

How do I reset the canvas upon button click? I attempted: cx.fillRect() However, the above method did not work as expected. I simply want to refresh the canvas without reloading the entire page. Below is my current code snippet: var canvas = docum ...

"Discover the steps to efficiently utilize the lookup feature with array objects in MongoDB

I am a beginner with MongoDB and I am trying to create a schema for my collection as shown below please note that all ObjectId values are placeholders and not real stockIn documents { serial:"stk0001", date:'2021-06-11', productInTra ...