Skip to content

Instantly share code, notes, and snippets.

@mlafeldt
Last active May 14, 2021 12:37
Show Gist options
  • Select an option

  • Save mlafeldt/3505b98399182a7afd2927fe86c583b0 to your computer and use it in GitHub Desktop.

Select an option

Save mlafeldt/3505b98399182a7afd2927fe86c583b0 to your computer and use it in GitHub Desktop.

Revisions

  1. mlafeldt revised this gist May 14, 2021. No changes.
  2. mlafeldt created this gist May 13, 2021.
    23 changes: 23 additions & 0 deletions useAuth0WithToken.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    import { useState, useEffect } from 'react'
    import { useAuth0 } from '@auth0/auth0-react'

    export const useAuth0WithToken = () => {
    const auth0 = useAuth0()
    const [token, setToken] = useState('')
    const [error, setError] = useState()

    useEffect(() => {
    if (!auth0.isAuthenticated) return
    auth0
    .getAccessTokenSilently()
    .then((token: string) => setToken(token))
    .catch((err) => setError(err))
    }, [auth0])

    return {
    ...auth0,
    isLoading: auth0.isLoading || (auth0.isAuthenticated && !token),
    error: auth0.error || error,
    token,
    }
    }