Typescript/react example code not compiling

Please include the following information in your post:

  • Which SDK this is regarding:
    @auth0/auth0-react”: “1.9.0”,
  • SDK Version: e.g. 2.29.0
    @auth0/auth0-react”: “1.9.0”,
  • Platform Version: e.g. Node 12.19.0
    “typescript”: “4.5.5”, && “react”: “17.0.2”,
  • Code Snippets/Error Messages/Supporting Details/Screenshots:

Copying from example code, the logout button works. Any lines reading user.picture, user.name, and user.email give the error “TS2532: Object is possibly ‘undefined’.” Is there a @types library to load so this will work and compile?

export default function Dashboard() {
    const { logout } = useAuth0();

    const { user, isAuthenticated, isLoading } = useAuth0();

    if (isLoading) {
        return <div>Loading ...</div>;
    }

    return (
    <div>
        <h1>Bookkeeper</h1>
        <nav
            style={{
                borderBottom: "solid 1px",
                paddingBottom: "1rem"
            }}
        >
            <Link to="/invoices">Invoices</Link> |{" "}
            <Link to="/expenses">Expenses</Link>
            <button onClick={() => logout({ returnTo: window.location.origin })}>
                Log Out
            </button>
            {isAuthenticated && (
            <div>
                <img src={user.picture} alt={user.name} />
                <h2>{user.name}</h2>
                <p>{user.email}</p>
            </div>
            )}
        </nav>
        <Outlet />
    </div>
);
}

Is this a feature request or bug report? If so, please create an issue directly in the corresponding GitHub repo. The Community SDK category is for general discussion and support.

I figured it out. Starting to get used to typescript finally. Basically, the example needs tweaking for typescript since user is ‘User | undefined’ and this fixes it →

            {
                user !== undefined && isAuthenticated && (
                    <div>
                        <img src={user.picture} alt={user.name} />
                        <h2>{user.name}</h2>
                        <p>{user.email}</p>
                    </div>
                )
            }
1 Like

Thanks for sharing it with the rest of community!

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.