Fetching locales asynchronously in nuxt.js using i18n and axios: A step-by-step guide

I am facing an issue with getting the location asynchronously. Whenever I try to implement my code, it results in a "Maximum call stack size exceeded" error. How can I resolve this issue?

Previously, I attempted to retrieve the location by using the axios command within the messages object.

~/plugins/i18n.js

import Vue from "vue";
import VueI18n from "vue-i18n";
import axios from 'axios';

Vue.use(VueI18n);

export default async ({ app, store }) => {
    app.i18n = new VueI18n({
    locale: 'fr',
    fallbackLocale: 'en',
    messages: {
        en: await axios.get('https://some-api/en/locale'),
        fr: await axios.get('https://some-api/fr/locale')
    }
});

}

My goal is to fetch my locales asynchronously before the page gets rendered.

Answer №1

If you want to fetch and set locale messages before creating a Vue instance, you can use the beforeCreate hook like this:

const localization = new VueLocalization();
new Vue({
  el: appElement,
  localization,
  beforeCreate() {
    const vueInstance = this;
    fetch(url)
      .then((res) => {
        vueInstance.$localization.setLocaleMessage('en', res.data);
    });
  }
});

Answer №2

To implement middleware, refer to: https://nuxtjs.org/api/pages-middleware#the-middleware-property

You can also retrieve data using axios from the module in the store and invoke it within nuxtServerInit:

export default actions {
async nuxtServerInit({dispatch}){
  await dispatch('apicallmodule/apicallAction')
}

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

Exploring Symfony2 controller integration with Javascript arguments

I am currently working on a project with Symfony2 and I have a question regarding receiving arguments from a template in a controller. My goal is to take the value of the argument and store it in the database. The argument's value will be generated by ...

Include a selection of images within a popover box

I am currently working on a component that contains various experiences, each with its own popover. My goal is to display an array of images within each popover. Specifically, I have different arrays of images named gastronomiaExperience, deportesExperien ...

Displaying components in a loop and utilizing the index in the child component's method (VueJS)

In my setup, I have two components that are involved in exchanging props. The props consist of the entire todo array which gets updated when a button is clicked using the "addTodo" method. Passing the array down to the child component works seamlessly. I a ...

Encountering Axios 404 error while trying to access the routes directory

My server.js file in Express and Node.js contains the bulk of my back-end code, except for my database config file. The file is quite lengthy, and I want to enhance maintainability by breaking it down into smaller modules that can be imported. To start t ...

utilize JavaScript on every element that has a specific identifier

<a id="link" href="http://www.google.co.uk">link</a> <a id="link" href="http://stackoverflow.com">link</a> Is there a way to make the JavaScript code apply to all <a> tags with the id="link", instead of just the first one? A ...

Is there a way to establish a connection with a secondary Firestore database in Node.js, allowing for the use of multiple Firestore databases

I have set up multiple firestore databases within my project. Using the command line, I created these databases and can view them in the Firestore Databases preview by following the instructions outlined here: https://cloud.google.com/blog/products/databas ...

Optimizing the file size of a Laravel app.js post Vuetify installation to reduce its

Incorporating vuetify into laravel to create a web admin, but my app.js file exceeds 6mb 7mb. Currently using laravel 5.8 and vuetify Any suggestions on how to decrease the file size? ...

Retrieve an item from a MongoDB database using Mongoose

It seems like a simple problem, but my brain is struggling to comprehend the issue at 2 AM. I'm working on creating a profile page that displays basic public information. My approach involves retrieving the user's username from MongoDB based on t ...

Renovating code structure in JavaScript

As I develop a small application that interacts with a database, I have opted to use Promises instead of the callback pattern for simplicity in my code. Through my coding experience, I've noticed a recurring pattern in my logic and I'm seeking ad ...

Tips for effectively utilizing the display: inline property in conjunction with ng-repeat

I am struggling to create a timeline with a broken structure on my website. I suspect that the issue lies in using display:inline. When attempting to apply this to my site: https://i.stack.imgur.com/4Ur7k.png the layout gets distorted: https://i.stack.i ...

You can disregard the first option in a multiple select box using jQuery

Imagine having multiple select boxes with the same options that are mutually exclusive. For instance, if Select Box A and Select Box B both have Option 1, Option 2, and Option 3, selecting Option 1 for Select Box A should make it unavailable in Select Box ...

Gauging Screen Size: A Comparison between Media Queries and JavaScript for Adjusting Div Position

I am currently facing an issue with the banner on my website. It contains a slider and has a position set to absolute. The problem arises when viewing it on smaller screens, as only the left side of the wide banner is visible. Initially, I tried using med ...

Endless AngularJS loop using ng-view

I recently started experimenting with AngularJS for a new project I am working on, but I have encountered a problem when dealing with routes and views. For the sake of simplicity, I have minimized this example to its basic form, yet the issue persists. Th ...

Dealing with JSON can sometimes create a challenge when working with the shape of React state, specifically when encountering

I have recently started working with React\Redux and have encountered an issue. I am trying to map some entities from a server API, but they get wrapped in an additional array level which prevents me from accessing them easily. Here is a snippet of my ...

Error: NgFor can only be used to bind to data structures that are iterable, such as Arrays. JSON arrays are

Encountering ERROR Error: Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables like Arrays. *ngFor="let spec of vehicleSpecs" Tried various solutions and searched extensi ...

Is there a way for my code to detect when a function and a timeout are in progress?

Is there a way to disable my button after just one click, or when the timeOut function is running? Currently, I have code that allows the button to be clicked only if my moneyValue is greater than money, and it's working perfectly. Now, within that sa ...

Using JavaScript to generate dynamic folders in Alfresco is not functioning as expected

Working with Alfresco 4.0.d community edition (also tested on Alfresco 4.0.c) on an Oracle Linux 64-bit virtual machine using Firefox. I've been developing a script to dynamically create sub-folders as new items are added to a space/folder via a rule ...

Repeated module imports

Currently, as part of my app development process, I am utilizing Parcel along with @material-ui/styles. One crucial aspect to note is that my app has a dependency on the @material-ui/styles package. Additionally, I have incorporated my own npm package, sto ...

Persisted state in Vuex fails to retain data after the page is refreshed

I recently added persisted state to my Vue application using the command npm install --save vuex-persistedstate. After that, I configured my Vuex store.js file in the following way: import Vue from 'vue' import Vuex from 'vuex' import ...

Display complete information of the selected list in a modal window by clicking on it in PHP Yii

I recently started working with the Yii framework and encountered a challenge when trying to pass data from a list to a modal using AJAX. The modal is located within the same view as the list. Here's a snippet of my code: This is my view: <div id ...