So I have this custom hook to decode a token
export function useToken(initial: string) {
const [token, setToken] = useState<string>(initial)
const [decoded, setDecoded] = useState<Token>()
useEffect(() => {
if (token) {
const value = decodeToken(token)
if (isTokenExpired(value)) {
setDecoded(undefined)
} else {
setDecoded(value)
}
} else {
setDecoded(undefined)
}
}, [token])
return [decoded, setToken]
}
The return type looks good, here a
[Token, React.Dispatch<React.SetStateAction<string>>]
I have another hook that uses this hook, but it's seeing the return type incorrectly
export function useUser() {
const [decoded, setToken] = useToken(getTokenFromStorage())
//...
Here useToken gives both decoded and setToken the same type of
Token | React.Dispatch<React.SetStateAction<string>>
i.e.
decoded: Token | React.Dispatch<React.SetStateAction<string>>, setToken: Token | React.Dispatch<React.SetStateAction<string>>
What am I doing wrong...
I got the same issue the other day!
You have to be explicit with the return type, as Typescript isn't inferring the type correctly.
For example:
export function useToken(initial: string): [Token, React.Dispatch<React.SetStateAction<string>>] {
}
That should fix it... I think it is a typescript bug so probably an issue needs to be made for it.
You may try to use "as const" at the end of the return. This is resolve issue.
return [decoded, setToken] as const
for more info check "const assertions"
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