Skip to content

Instantly share code, notes, and snippets.

@klequis klequis/react-auth0-spa.js
Last active Sep 18, 2019

Embed
What would you like to do?
Modification to Auth0Provider in react-auth0-spa.js
import React, { useState, useEffect, useContext } from 'react'
import createAuth0Client from '@auth0/auth0-spa-js'
const DEFAULT_REDIRECT_CALLBACK = () =>
window.history.replaceState({}, document.title, window.location.pathname)
export const Auth0Context = React.createContext()
export const useAuth0 = () => useContext(Auth0Context)
let _initOptions
const getAuth0Client = () => {
return new Promise(async (resolve, reject) => {
let client
if (!client) {
try {
client = await createAuth0Client(_initOptions)
resolve(client)
} catch (e) {
reject(new Error('getAuth0Client Error', e))
}
}
})
}
export const getTokenSilently = async (...p) => {
const client = await getAuth0Client()
return await client.getTokenSilently(...p)
}
export const Auth0Provider = ({
children,
onRedirectCallback = DEFAULT_REDIRECT_CALLBACK,
...initOptions
}) => {
const [isAuthenticated, setIsAuthenticated] = useState()
const [user, setUser] = useState()
const [auth0Client, setAuth0] = useState()
const [loading, setLoading] = useState(true)
const [popupOpen, setPopupOpen] = useState(false)
useEffect(() => {
const initAuth0 = async () => {
_initOptions = initOptions
const client = await getAuth0Client(initOptions)
setAuth0(client)
if (window.location.search.includes('code=')) {
const {
appState
} = await client.handleRedirectCallback()
onRedirectCallback(appState)
}
const isAuthenticated = await client.isAuthenticated()
setIsAuthenticated(isAuthenticated)
if (isAuthenticated) {
const user = await client.getUser()
setUser(user)
}
setLoading(false)
}
initAuth0()
// eslint-disable-next-line
}, [])
const loginWithPopup = async (params = {}) => {
setPopupOpen(true)
try {
await auth0Client.loginWithPopup(params)
} catch (error) {
console.error(error)
} finally {
setPopupOpen(false)
}
const user = await auth0Client.getUser()
setUser(user)
setIsAuthenticated(true)
}
const handleRedirectCallback = async () => {
setLoading(true)
await auth0Client.handleRedirectCallback()
const user = await auth0Client.getUser()
setLoading(false)
setIsAuthenticated(true)
setUser(user)
}
return (
<Auth0Context.Provider
value={{
isAuthenticated,
user,
loading,
popupOpen,
loginWithPopup,
handleRedirectCallback,
getIdTokenClaims: (...p) => auth0Client.getIdTokenClaims(...p),
loginWithRedirect: (...p) => auth0Client.loginWithRedirect(...p),
getTokenWithPopup: (...p) => auth0Client.getTokenWithPopup(...p),
logout: (...p) => auth0Client.logout(...p)
}}
>
{children}
</Auth0Context.Provider>
)
}
@stevehobbsdev

This comment has been minimized.

Copy link

commented Jul 12, 2019

@klequis Looking at the code, is the only change the fact that getTokenSilently is exported?

I wonder if it's better to export the whole Auth0Client instance from the module rather than do it method by method.

@klequis

This comment has been minimized.

Copy link
Owner Author

commented Jul 13, 2019

For my immediate need the only thing that needs to be outside of the hook is getTokenSilently. I haven't thought of a use case where any of the other methods would need to be.

On the other hand isAuthenticated and loading need to get into props so changes trigger render and doing that with a provider seems a good approach. Having the user info available from the provider is also convenient.

I don't really like having one part of of it available via one mechanism and another part via another mechanism but I don't see a better choice.

I do think having the Auth0Client methods wrapped and setting isAuthenticated & loaded the way it is being done is beneficial as if it were not, people would just wrap it themselves because that functionality is needed.

I played with it a bit today but didn't come to any final conclusion. Will do some more in the next few days.

Cheers

@thekamahele

This comment has been minimized.

Copy link

commented Aug 25, 2019

@klequis Things seem to work fine the first time around, but on refresh I keep getting a getAuth0Client error. Have you run into this at all?

@klequis

This comment has been minimized.

Copy link
Owner Author

commented Aug 28, 2019

@thkamahele

I did have a similar problem on an earlier iteration of this code where the client (line 44) would fall out of scope. To solve it I wrote the getAuth0Client() function and have not had a problem since.

Can you reply with the full error message you are getting?

@aparry3

This comment has been minimized.

Copy link

commented Sep 6, 2019

What is the let client doing on line 14. Maybe this is JS ignorance issue. Why would client exist on the check on the next line?

@niallmc

This comment has been minimized.

Copy link

commented Sep 18, 2019

@klequis I have tried using this, but it seems to be asking for a new token on every call of getTokenSilently when I use it.

update: This is what I did to resolve my issue:

let _initOptions, _client

const getAuth0Client = () => {
  return new Promise(async (resolve, reject) => {
    let client
    if (!client)  {
      try {
        client = await createAuth0Client(_initOptions)
        resolve(client)
      } catch (e) {
        reject(new Error('getAuth0Client Error', e))
      }
    }
  })
}

export const getTokenSilently = async (...p) => {
  if(!_client) {
      _client = await getAuth0Client()
  }
  return await _client.getTokenSilently(...p)
}
@thekamahele

This comment has been minimized.

Copy link

commented Sep 18, 2019

I'm having the same issue as @niallmc, and similar code but I'm still getting this error:

auth0-spa-js.production.js:1026 Uncaught TypeError: Cannot read property 'close' of undefined at o

I'm thinking it might be related to this issue

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.