'Custom React Hook typescript error on array return type
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.
Solution 1:[1]
I had a similar problem, I got advice from another programmer to add as const
for return
return [language, setLanguage] as const
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | blackenergy1645 |