Utilizing Vue.js and i18n to fetch external JSON files from a server and seamlessly integrating them as globally accessible data in all components

I'm currently exploring ways to fetch translation files from a server and make them accessible across all components of the project.

For instance, I can request to obtain this JSON:

{
    "DASHBOARD_SETTINGS": "Einstellungen",
    "DASHBOARD_CUSTOMERS": "Kunden",
    "DASHBOARD_CAMPAIGNS": "Kampagnen",
    "DASHBOARD_LOCATIONS": "Standorte",
    "DASHBOARD_DISPLAYS": "Displays"
}

This illustrates my file structure:

  • router.js
  • i18n_setup.js
  • app.js
  • components
    • Dashboard.vue

i18n_setup.js

import Vue from 'vue'
import VueI18n from 'vue-i18n'

Vue.use(VueI18n)

export const i18n = new VueI18n({
    locale: 'de',
    fallbackLocale: 'en'
})

const loadedLanguages = ['de']

function setI18nLanguage (lang) {
    i18n.locale = lang
    axios.defaults.headers.common['Accept-Language'] = lang
    document.querySelector('html').setAttribute('lang', lang)
    return lang
}

export function loadLanguageAsync (lang) {
    if (typeof lang === 'undefined') {
        lang = window.navigator.userLanguage || window.navigator.language;
        lang = lang.slice(0,2);
    }
    if (loadedLanguages.includes(lang)) {
        if (i18n.locale !== lang) setI18nLanguage(lang)
        return Promise.resolve()
    }
    return fetch(`https://EXAMPLE.de/locales?lang=${lang}`)
        .then(response => {
            let msgs = response.data
            loadedLanguages.push(lang)
            i18n.setLocaleMessage(lang, msgs)
            return setI18nLanguage(lang)
        });
}

router.js

...
router.beforeEach((to, from, next) => {
    const lang = to.params.lang
    loadLanguageAsync(lang).then(() => next())
})

app.js

...
// i18n
import { i18n } from './i18n_setup'
...
const app = new Vue({
    store,
    i18n,
    el: '#app',
    components: {
        App
    },
    router
});

Dashboard.vue

import { loadLanguageAsync } from '../i18n_setup'

While I can observe the translations being fetched in the network tab of the browser, attempting to access a translation using something like {{ $t('DASHBOARD_SETTINGS') }} triggers a warning/error:

[vue-i18n] Cannot translate the value of keypath 'DASHBOARD_SETTINGS'. Use the value of keypath as default.

Any insights into what might be missing here?

Answer №1

fetch retrieves an object categorized as Response. When you try to access response.data, note that this property does not exist on the Response object (let msgs = response.data)

To extract data from the response, utilize response.json()

return fetch(`https://EXAMPLE.de/locales?lang=${lang}`)
  .then(response => response.json())
  .then(msgs => {
     loadedLanguages.push(lang)
     i18n.setLocaleMessage(lang, msgs)
     return setI18nLanguage(lang)
   });

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

Having trouble retrieving information from a nested JSON array within a JSON object using JavaScript

I am facing a challenge with extracting specific information from a JSON object that contains an array nested inside. Even though I have experience working with JSON arrays, this particular object is proving to be tricky. For example, when attempting to r ...

Vite build error: TypeError - Unable to access properties of null while trying to read 'useContext'

I used the following component imported from material-ui : import Paper from '@mui/material/Paper'; After running npm run build followed by npm run preview, I encountered an error in the console: Uncaught TypeError: Cannot read properties of n ...

The method item.appendChild does not exist as a function

Despite being a common error, I've researched extensively and still can't figure out why it's happening. It seems like it should be an easy fix, but I'm struggling to find the solution on my own. var item = document.createElement("div" ...

Progress bar displaying during Ajax request

I'm currently working on an Ajax request that uploads images to the Imgur API and I want to implement a progress bar to show users the upload progress. I found some guidance in this thread, but it seems to display only 1 and stop working. This is the ...

Uncovering the Mystery of Undefined Dom Ref Values in Vue 3 Templaterefs

I am currently experimenting with the beta version of Vue 3 and encountering an issue while trying to access a ref in the setup function. Here is my component: JS(Vue): const Child = createComponent({ setup () { let tabs = ref() console.log(t ...

Implementing dynamic option selection in Vue using JavaScript and v-model

Is there a way to manage the chosen value in a v-modeled select tag using vue.js? I created a jsFiddle demonstration, but unfortunately, it is not functioning correctly. This leads to my inquiry: vm.$set('selected', '1') // does not wo ...

How can Node.js and Express be used to conceal Javascript code on the backend?

I'm a beginner when it comes to Node and Express. I have a query regarding how to securely hide Javascript code on the backend. Currently, I am working with Node.js and Express. My goal is to prevent users from easily accessing the code through browse ...

Exploring the function of variables in VueJS

I'm facing a tricky issue with VueJS as I am still getting acquainted with it. My objective is to access and modify variables within the data function, but so far, I haven't been successful. The problematic line: console.log('item: ' ...

Having trouble with the Ajax load function not functioning in your HTML code?

The issue has been resolved. Thank you to everyone who helped! Initially, I was attempting to run a file offline instead of on a web server (XAMPP server). Once I uploaded the file to the web server, it started working properly. I had been trying to load ...

Retrieving Files using Ajax Across Different File Types

I recently came across the following code snippet: DOM_imgDir = "img/UI/DOM/"; fileextension = ".jpg"; $.ajax({ url: DOM_imgDir, success: function (data) { $(data).find("a:contains(" + fileextension + ")").each(function () { filename = thi ...

Ways to determine if a user is using a PC using JavaScript

I am developing a website using node.js that will also serve as the foundation for a mobile app. The idea is to have users access the website on their phones and use it like an app. But I want to implement a feature that detects when the site is being vi ...

Conceal or remove disabled years in Angular Material datepicker

I previously disabled years prior to 2018, but now I would like to hide or delete them. The year selection range currently starts from 1998, but it should begin at 2018 instead. Is there a way to display only 3-4 years instead of the current 24-year rang ...

Invoking a C++ dll in the renderer process of a Node.js application with Electron using node ffi

As I work on developing a windows application using electron, my goal is to utilize the ffi-napi to invoke C++ .dll methods. However, I am facing a challenge with the "Passing_Dll.js" file, where the label with id "GenName" is not being updated when clicki ...

How to Create a DataTable Responsive Feature Where All Columns Collapse on Click, Except the Last One?

I am currently utilizing the DataTables library to generate a responsive table. I am aiming to create a feature where all columns in the DataTable can toggle between collapse and expand states when clicked, with the exception of the last column. Below is a ...

Ionic ion-view missing title issue

I'm having trouble getting the Ionic title to display on my page: http://codepen.io/hawkphil/pen/oXqgrZ?editors=101 While my code isn't an exact match with the Ionic example, I don't want to complicate things by adding multiple layers of st ...

The function $(...) does not recognize tablesorter

Currently, I am encountering issues with the tablesorter plugin as my system is unable to recognize the existing function. It is unclear whether there might be a conflict with other JavaScript files, especially since I am implementing changes within a Word ...

Preventing Duplicate Random Numbers in Vue 3 and JavaScript: A Guide

I've been working on creating a function that can iterate through an array of objects with names and IDs, randomize the array, and then return one filtered item to slots.value. The current spin function successfully loops through the randomized object ...

Safeguarding intellectual property rights

I have some legally protected data in my database and I've noticed that Google Books has a system in place to prevent copying and printing of content. For example, if you try to print a book from this link, it won't appear: How can I protect my ...

"Send the selected radio button options chosen by the user, with the values specified in a JSON format

My current task involves inserting radio button values into a MySql database using Angular. The form consists of radio buttons with predefined values stored in a json file. Below is an example of how the json file is structured: //data.json [{ "surve ...

Grin schedule module JSON stream

I have integrated a Smile timeline widget on my website and successfully customized it following several tutorials. However, I am struggling to utilize a Json service instead of relying on data stored in a global variable within a JavaScript file. Despite ...