Unable to retrieve translations using language header in axios are not successful

My goal is to create a single-page website with multiple components. I am facing an issue where only one language appears instead of fetching translations from the API for each component. When using Promise.all() in the index page, the translations do not display as expected. The strange thing is that when I make individual axios.get() calls for each component, it works fine. How can I troubleshoot this problem and find a solution?

header.js

import Link from 'next/link';
import { useRouter } from 'next/router';
import en from './locales/en';
import ar from './locales/ar';
import Axios from 'axios';
import Cookie from 'js-cookie';
import {useState } from 'react';

const Header = () => {
    const router = useRouter();
    const [langCode, setLangCode] = useState('en');    
    Axios.defaults.headers.common['Language'] = langCode;

    const { locale } = router;
    const t = locale === 'en' ? en : ar;

    const changeLanguage = (locale) => {
        Cookie.set('lang', locale);
        router.push(router.pathname, router.asPath, { locale });
        setLangCode(locale);

    };

    const lang = Cookie.get('lang');

    return (
        <header>
            <button onClick={() => changeLanguage(lang == 'en' ? 'ar' : 'en')}>
                Change Language
            </button>
            <ul>
                <li>
                    <Link href="/">
                        <a>{t.home}</a>
                    </Link>
                </li>
            </ul>
        </header>
    );
};

export default Header;

index.js

import Axios from "axios";
import Header from "../components/Header";

const Index = ({ data }) => {
  return (
    <div>
      <Header />
      <div dangerouslySetInnerHTML={{ __html:  data.details}}/>
    </div>
  );
};

Index.getInitialProps = async () => {
  const res = await Axios.get(`https://api.trueapps.co/api/who-we-are`);
  const data = await res.data.data;
  return { data };
};

export default Index;

This code snippet below demonstrates the usage of Promise.all() in index.js.

index.js

import Axios from "axios";
import Header from "../components/Header";

const Index = (data) => {
    console.log(data.about);
    console.log(data.services);
    console.log(data.team);
    return (
        <div>
            <Header />
        </div>
    );
};

Index.getInitialProps = async () => {

    const [about, team, services] = await Promise.all([
        fetch(`https://api.trueapps.co/api/who-we-are`).then((r) => r.json()),
        fetch(`https://api.trueapps.co/api/team`).then((r) => r.json()),
        fetch(`https://api.trueapps.co/api/services`).then((r) => r.json()),
    ]);

    return { about, team, services };

};

export default Index;

Answer №1

The main concern lies in the fact that the default Language header is being set in axios (

Axios.defaults.headers.common['Language'] = langCode;
), but the requests are being made using fetch.

To resolve this issue, it is recommended to use axios for making requests in the index.getInitialProps function.

index.getInitialProps = async () => {
    const [aboutRes, teamRes, servicesRes] = await Promise.all([
        Axios.get(`https://api.trueapps.co/api/who-we-are`),
        Axios.get(`https://api.trueapps.co/api/team`),
        Axios.get(`https://api.trueapps.co/api/services`)
    ]);
    return {
        about: aboutRes.data,
        team: teamRes.data,
        services: servicesRes.data
    };
};

Answer №2

It seems like you may be confusing Axios and the fetch API in your code. Consider using Axios's get method instead of mixing it with fetch API.

index.getInitialProps = async () => {

    const [about, team, services] = await Axios.all([
        await fetch(`https://api.trueapps.co/api/who-we-are`).then((r) => r.json()),
        fetch(`https://api.trueapps.co/api/team`).then((r) => r.json()),
        fetch(`https://api.trueapps.co/api/services`).then((r) => r.json()),
    ]);
        return { about, team, services};

};

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

Building a custom tooltip for a Bootstrap multiselect dropdown menu

I have been attempting to implement a tooltip on a multiselect dropdown menu that I constructed using the Bootstrap-select jQuery plugin... Here is how I coded my select in the HTML... <select id="dropDownList" class="selectpicker" t ...

Attempting to modify the inner element through get element, but encountering a TypeError: Unable to assign value to 'innerHTML' property of null

I'm having trouble updating an element using the getElementById method and I keep getting this error message: TypeError: Cannot set property 'innerHTML' of null. Are there other ways to pass parameters or is this the right approach? This ...

The AddClass function fails to function properly after an ajax form is submitted

I am facing a challenge in setting up validation for my ajax form. My goal is to have a red border appear around the input field if it is submitted empty. Unfortunately, when I try to use addClass(), it does not seem to have any effect. The alert message ...

Embed a Telegram account onto an HTML page using the <iframe> element

Is there a way to display the personal Telegram account in an iframe tag? I experimented with the code below, but unfortunately it did not produce the desired result: <iframe src="https://telegram.me/joinchat/BfNEij9CbDh03kwXacO5OA"></iframe> ...

Utilizing CSS files to incorporate loading icons in a component by dynamically updating based on passed props

Is it possible to store icons in CSS files and dynamically load them based on props passed into a component? In the provided example found at this CodeSandbox Link, SVG icons are loaded from the library named '@progress/kendo-svg-icons'. Instea ...

Struggling to eliminate the scrollbar on a Material UI Dialog

I have a modal window that includes a keyboard, but I'm encountering some issues. Despite adding overflow:'hidden' as inline CSS, the scrollbar refuses to disappear. Furthermore, even when utilizing container-full padding-0 in Bootstrap, th ...

Limiting the display of JSON data on a webpage using jQuery

I have a code snippet on my website that displays JSON data on an HTML page. The issue is that there is a large amount of data in the JSON file. How can I limit the number of movies (data) being displayed to just 5? function actors(actors) { return ` ...

Interactive KML layer in ArcGIS mapping tool

Currently, I am working on enhancing an ArcGIS map by incorporating KML layers for interactivity. This is a simplified version of the code I am currently using: map = new Map("map", { basemap: "topo", center: [-108.663, 42.68], zoom: 6 }); parser.p ...

Receiving information from mongoose server, yet encountering an empty array in React

Whenever I attempt to retrieve data from MongoDB using React, it only shows an empty array when utilizing a useEffect. The data is only displayed if I make changes on the page. Additionally, when trying to map over the data, nothing appears: Server-Side: ...

Having trouble with a basic API Get request?

I'm trying my hand at making a simple get request to fetch a random quote from an API. When I hardcode the change of the quote on button click, everything works smoothly. $(document).ready(function() { $("#quotebtn").on('click', functio ...

Tips for troubleshooting the StaleElementReferenceError in selenium automation

Encountering the persistent issue of receiving the error message StaleElementReferenceError: stale element reference: element is not attached to the page document every time I attempt to extract the text from a page body using Selenium. Numerous attempts h ...

Import a JSON file and convert it into an array using JavaScript

I've got a json file that resembles the following: easy.txt {"top":[[1],[2,2],[2,2,3],[7,2],[2,3],[2,3],[2,2,3],[7,2],[2,2,3],[2]],"left":[[1,1],[3,3],[3,3],[1,1],[3,4],[3,4],[1,1],[3,3,2],[9],[7]],"task":[[0,0,0,1,0,0,0,1,0,0],[0,0,1,1,1,0,1,1,1,0] ...

Using AngularJS to Create Dynamic Radio buttons through ng-repeat

I have a group of radio buttons that are generated using an ng-repeat directive, following the guidance provided in this helpful answer. However, I am struggling to understand how to integrate an ng-model into this setup. <tr ng-repeat="service in s ...

Using jQuery and regex to only allow alphanumeric characters, excluding symbols and spaces

Seeking advice, I am using a jquery function called alphanumers var alphanumers = /^[a-zA-Z0-9- ]*$/; which currently does not allow all symbols. However, I now wish to disallow the space character as well. Any suggestions? ...

Canvas.js graph failing to refresh with updated data

I have encountered an issue while using CanvasJS to generate a line graph with data from Myo. The problem is that when new data is received, the graph fails to update. This may be due to the fact that I did not initially populate the graph with any data po ...

The function WebGLRenderer() from three.js allows for rendering in

When initializing the WebGLRenderer, I am passing in a canvas DOM element like shown below: var jqc = $('#myCanvas'); //accessing canvas with jQuery; var par = {canvas:jqc.get()}; //creating parameter object with canvas DOM element var renderer ...

How can we implement a feature that allows users to save a page as a bookmark by clicking a specific button, and then store that bookmarked page link in their user profile for easy access

Is it feasible to create a function where clicking on a specific button saves the current page as a bookmark, storing the link in the user's account on the website instead of saving it directly into the browser? I am looking to implement this feature ...

Creating a dynamic interaction between HTML forms and JavaScript using the onsubmit event handler

Having trouble getting my JavaScript file to fire when clicking the submit button on my simple HTML form. Can anyone provide some assistance? **UPDATED CODES Here is a snippet of my condensed HTML file: <html> <form name="form01" id="form01" ac ...

An empty array is being returned by the Model.find() method after sorting

let query = Tour.find(JSON.parse(queryStr)); if (req.query.sort) { query = query.sort(req.query.sort);//a string 'ratings' } const tours = await query; res.status(200).json({ status: 'success', requestedAt: req.requestTime, ...

JavaScript Scroller that keeps on scrolling

Unique Continuous JavaScript Scroller I am currently working on a JavaScript scroller script that enables left to right and right to left scrolling on the click of next and previous buttons. The script is designed to work with 1 to 3 div elements in a con ...