Skip to content

Instantly share code, notes, and snippets.

@glaucomunsberg
Created November 28, 2023 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glaucomunsberg/726fdfc18cb7db6392a7d061af5df4ee to your computer and use it in GitHub Desktop.
Save glaucomunsberg/726fdfc18cb7db6392a7d061af5df4ee to your computer and use it in GitHub Desktop.
react-intl with yml file with typescript
// 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