Created
November 28, 2023 16:52
-
-
Save glaucomunsberg/726fdfc18cb7db6392a7d061af5df4ee to your computer and use it in GitHub Desktop.
react-intl with yml file with typescript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// yarn add js-yaml react-intl @types/js-yaml | |
import yaml from 'js-yaml'; | |
import { IntlProvider } from 'react-intl'; | |
import { useEffect, useState } from 'react'; | |
import Routes from './Routes'; | |
const loadYaml = async (filePath:string) => { | |
try { | |
const response = await fetch(filePath); | |
const yamlContent = await response.text(); | |
const data = yaml.load(yamlContent); | |
return data; | |
} catch (error) { | |
console.error('Error loading YAML file:', error); | |
throw error; | |
} | |
}; | |
function App() { | |
const [yamlData, setYamlData] = useState<object>({}); | |
useEffect(() => { | |
const loadYamlData = async () => { | |
try { | |
const data:unknown = await loadYaml('/locales/locale_messages.yml'); | |
const data_to:object = data as object; | |
setYamlData(data_to); | |
} catch (error) { | |
// Handle error loading YAML file | |
} | |
}; | |
loadYamlData(); | |
}, []); | |
if (Object.keys(yamlData).length == 0) { | |
return null; | |
} | |
const locale:string = localStorage.getItem('locale') || 'pt-BR'; | |
// @ts-expect-error: Unreachable code error | |
const messages = yamlData[locale]; | |
return ( | |
<IntlProvider key={ locale } locale={ locale } messages={messages}> | |
<Routes /> | |
</IntlProvider> | |
); | |
} | |
export default App |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment