I've created a very simple custom hook:
export function useI18n() : [ string, Dispatch<SetStateAction<string>> ] {
const [ language, setLanguage ] = useState<string>(i18n.language)
useEffect(() => {
i18n.changeLanguage(language)
}, [ language ])
return [ language, setLanguage ];
}
And in my components I use this hook like this:
const [language, setLanguage] = useI18n();
I'm using react-scripts, and when I do npm start
I get the following:
Failed to compile.
./src/config/i18n.ts
Line 0: Parsing error: Cannot read property 'map' of undefined
However this error doesn't happen if I setup my hook to return an Object instead of an Array, like this:
export function useI18n() : { language: string, setLanguage: Dispatch<SetStateAction<string>> } {
const [ language, setLanguage ] = useState<string>(i18n.language)
useEffect(() => {
i18n.changeLanguage(language)
}, [ language ])
return { language, setLanguage };
in which case I call it like this:
const { language, setLanguage } = useI18n();
Anybody understand why returning the array causes a compilation failure? Maybe I'm making some strange mistake. Thanks in advance.
I had a similar problem, I got advice from another programmer to add as const
for return
return [language, setLanguage] as const
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With