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

Tips for sending <p> data to a router function with HTML

I am currently working on a page where users are presented with a list of unverified accounts, each containing its own form element. Each form has a "submit" button that triggers a POST call to /verify. However, I am facing an issue where the data within t ...

Implementing a nested ng-repeat for organizing limited data

I'm working with a nested ng-repeat setup like this: <div ng-repeat="item_l in list1"> <div ng-repeat="item_f in list2"> {{item_f}} {{item_l}} </div> </div> Currently, this code is producing around 20 results. ...

Guidelines for incorporating role-based permissions in a React application

I am developing a MERN application that has various features catering to different roles. I need the ability to display specific data, navigation options, and divs based on the user's role while hiding these elements from others. It is important to no ...

refusing to display the pop-up in a separate window

Hi there, I'm having an issue with a link that's supposed to open in a pop-up but is instead opening in a new tab. I'd like it to open in a proper pop-up window. <button class="button button1" onclick=" window.open('te ...

Dynamic Website (Link Relationships / Responsive Design / Content Rendering with CSS and HTML)

Hello everyone! My name is Mauro Cordeiro, and I come from Brazil. I am just diving into the world of coding and have been following various tutorials. Stack Overflow has been an invaluable resource for me in my learning journey! Aside from coding, I am a ...

Having issues with JavaScript and MySQL data retrieval following XMLHttp update to the database

After running the newNet.php file successfully creates a new entry and assigns it an auto-incremented netID. The next step is to retrieve this newly created ID and use it in the showActivities() function to display the record. Ideally, it should work like ...

How to navigate to the next page in Vue form submission in Laravel

Currently, I am utilizing both Laravel and Vue to create a form that should redirect to another page upon submission. However, the issue lies in the fact that after submission, the form refreshes and returns to the same page instead of redirecting to the s ...

Slick slider issue: Unexpected TypeError - the slick method is undefined for o[i]

I'm facing an issue where, upon clicking the search button, I want the previous search results to clear and new ones to be displayed. However, this action triggers a slick slider error, causing all items to align vertically instead of in the intended ...

Toggle jQuery to hide a div and update its CSS styling

There is an anchor with the class of "hide-btn1" that I want to trigger a series of actions when clicked: The rcol-content should hide and the text should change from Hide to Show The #container width needs to increase to 2038px The table.status-table wi ...

Having trouble dividing an HTML file?

Currently, I am working on creating a very basic web page that is divided into two parts. Each part will have its own HTML file: Welcome.html & Welcome.css: <html> <head> <link rel="stylesheet" type="text/css" href="Welcom ...

Tips for resolving the issue of Vue 3 router with multiple calls to next()

Currently, I am tackling the router functionality of my web application. Each time I use "next" to navigate to a specific section, I encounter an issue where it indicates that I have invoked next() multiple times and warns about potential failures in produ ...

Utilizing NextJS to retrieve cookie data within React components

Currently, I am working with a Next.js frontend and an Express backend. For authentication, I am utilizing cookies and have set up protected routes using Next.js middleware. The next step in my project involves accessing the cookie response within React ...

Dynamically taking input in Vue JS while using v-for loop

Hey there! I'm trying to get input in this specific manner: itemPrices: [{regionId: "A", price: "200"},{regionId: "B", price: "100"}] Whenever the user clicks on the add button, new input fields should be added ...

Tips for properly formatting functional Vue components?

Below is a functional component that functions as intended. <template functional> <div> <input /> </div> </template> <script> export default { name: "FunctionalComponent" } </script> <styl ...

Angular 8 fails to retain data upon page refresh

I have a property called "isAdmin" which is a boolean. It determines whether the user is logged in as an admin or a regular user. I'm using .net core 2.2 for the backend and Postgre for the database. Everything works fine, but when I refresh the page, ...

What is the best way to merge setInterval with mouseenter events?

I have successfully implemented code that refreshes a div using ajax. However, I am looking to add functionality so that the div only refreshes every 30 seconds when the tab is active. It seems that setInterval currently refreshes the div regardless of tab ...

Having trouble sending values via POST request in Node.js using Express

Currently, I am in the process of learning how to use Express (v4) with Node.js. My main goal right now is to create a basic REST API. This API specifically focuses on one endpoint: /orders. The main functionality I am trying to achieve is the ability to r ...

Creating a step wizard form with ReactJs can be accomplished by breaking down the form into

I have developed a resume generation application with two main components: BasicDetails and EmploymentDetails. To see a working example, click here: https://codesandbox.io/s/next-dynamic-testing-issue-forked-h1nt8 index.js file: <form onSubmit={ha ...

What is the best way to showcase the information of each object on a click event in Vue.js?

My goal with this code is to display each day's class schedule when it is clicked on. However, the issue I'm facing is that the entire week's schedule is being displayed instead of just the selected day. What adjustments should I make in ord ...

I am facing an issue where the module pattern functions perfectly on JSBin, but fails to work properly

As a backend developer, I typically only write JavaScript when absolutely necessary, and not always in the best way. However, I have decided to turn over a new leaf and start writing more organized code that follows best practices as much as possible. To ...