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;