I have created a MessageLabel component, which is used as follows:
<button><MessageLabel>signin</MessageLabel></button>
The MessageLabel component uses the placeholder label as a key to find the actual label value in the object that is being fetched by the Translator component. Currently the language is not configurable by the user, but is included in the API request for future proofing.
import Translator from "./translation_provider";const MessageLabel = (msgKey) => { const key = msgKey.children; const getMessageKey = () => { if (Translator.messages){ return Translator.messages[key] } else { return key } } return ( getMessageKey() );};export default MessageLabel;
The Translator component:
import { useState } from "react";import axios from "../api/axios"import config from '../config/config';const FetchTranslations = async (lang) => { const langURL = config.TRANSLATIONS_URL +"/" + lang; const [waitingForResponse, setWaitingForResponse] = useState(false); setWaitingForResponse(true); try { const response = await axios.get( langURL, config.HEADERS ); if (response.data){ for (var id in response.data.language) { Messages[response.data.language[id].msgKey] = response.data.language[id].message; } Translator.setMessages(Messages); return Messages } } catch(err) { // TODO - catch errors }}const Translator = () => { const [messages, setMessages] = useState({}); if (messages == {}){ setMessages(FetchTranslations('bg')); // TODO - make language configurable by user }}export default Translator```The Translator component sends a GET request to the API endpoint set up in the config file. The API request does return the correct data in the correct format.What I'm expecting to see is the label with the placeholder text until the translations are received and then to have them replaced with the actual texts. However they are not getting replaced and I can't figure out why. I suspect I'm not using the hooks correctly.