Using Auth with class components
There's very scarce documentation on how to use this library with class components. I found this example:
import React, { Component } from 'react';
import { withAuth0 } from '@auth0/auth0-react';
class Profile extends Component {
render() {
const { user } = this.props.auth0;
return <div>Hello {user.name}</div>;
}
}
export default withAuth0(Profile);
Now I want to achieve something like this:
import React, { Component } from 'react';
import { withAuth0 } from '@auth0/auth0-react';
class Profile extends Component {
render() {
const { user } = this.props.auth0;
const isAuthenticated = ??? // <---- how do I get this value?
return isAuthenticated ? renderAuthenticatedUser(user) : renderUnauthenticatedUser();
}
}
export default withAuth0(Profile);
How do I do this? I've been reading through the docs and scratching my head for quite a while..
Hi @agaace - thanks for raising this
this.props.auth0 has all the same properties (auth state and auth methods) that the useAuth0 hook has. so you can use it to get the isAuthenticated property:
import React, { Component } from 'react';
import { withAuth0 } from '@auth0/auth0-react';
class Profile extends Component {
render() {
const { user, isAuthenticated } = this.props.auth0;
return isAuthenticated ? renderAuthenticatedUser(user) : renderUnauthenticatedUser();
}
}
export default withAuth0(Profile);
Let me make a change to the docs that should make this a bit clearer
Your solution is not working for me. IsAuthenticated is ALWAYS false and it never changes to true. There's never any lifecycle event that would update this value (I tried componentDidUpdate, willReceiveProps and the new combo that's in place of the deprecated willReceiveProps). Any ideas how to listen for updates?
Hi @agaace - are you still seeing this issue? I wasn't sure from you're other comment whether you'd resolved this or not
sorry to raise a closed ticket, but how does one go about getting the user's token (ie the 'getAccessTokenSilently' flow) when using a class component? I'm running into the same issues of difficulty when not using hooks.
@Cammac7
import React, { Component } from 'react';
import { withAuth0 } from '@auth0/auth0-react';
class Products extends Component {
componentDidMount() {
const { getAccessTokenSilently } = this.props.auth0;
getAccessTokenSilently()
.then(token => fetch(`https://my-api.com/products`, { headers: authorization: `Bearer ${token}` }))
.then(res => res.json())
.then(json => this.setState({ data: json }));
...
}
}
export default withAuth0(Products);
Thank you so much!