4

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...

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.