lhoist-stay-safe/src/context/UserContext.js

64 lines
1.7 KiB
JavaScript

import { createContext, useEffect, useState } from "react";
import CountriesJSON from "../data/countries/countries.json";
export const UserContext = createContext();
export function UserContextProvider({ children }) {
const [language, setLanguage] = useState("FR");
const [country, setCountry] = useState({ name: "belgique", iso: "BE", label: "Belgique" });
const [profile, setProfile] = useState("lhoist_employee");
const [screensTranslations, setScreensTranslations] = useState({});
useEffect(() => {
if (!language) return;
const loadTranslations = async (language) => {
try {
const translations = await import(`../data/screensTranslations_${language}.json`);
setScreensTranslations(translations.default);
} catch (error) {
console.error("Could not load translations", error);
}
};
// Appeler la fonction loadTranslations avec la langue actuelle
loadTranslations(language);
// ADAPTING COUNTRY LABEL TO LANGUAGE
const currentCountry = CountriesJSON.find(
(countryJson) => countryJson.alpha2 === country.iso.toLowerCase()
);
setCountry({ ...country, label: currentCountry[language.toLowerCase()] });
}, [language]);
function changeLanguage() {
if (language === "FR") {
setLanguage("EN");
} else {
setLanguage("FR");
}
}
function changeCountry(newCountry) {
setCountry(newCountry);
}
function changeProfile(newProfile) {
setProfile(newProfile);
}
return (
<UserContext.Provider
value={{
language,
screensTranslations,
changeLanguage,
country,
setLanguage,
changeCountry,
profile,
changeProfile,
}}>
{children}
</UserContext.Provider>
);
}