0

I have a functional component Profile, I only want users to access it if they are authenticated, if not, they should be redirected.

import React from 'react';
import {useAuth0} from '@auth0/auth0-react';

export const Profile = ({history}) => {
  const {user, isAuthenticated} = useAuth0();

  if (!isAuthenticated) history.push('/');
  const {email, picture} = user;

  return (
    <div>
      <h4>Profile</h4>
      <p>{email}</p>
      <p>{picture}</p>
    </div>
  );
}; 

Here I get an error if I try to access the /profile directly.

`TypeError: Cannot destructure property 'email' of 'user' as it is` undefined.

What I would like to do is the following:

  • render the Home component if the user is not authenticated and pass a props boolean.
  • redirect the app to '/'

I am trying to combine history.push('/') and return <Home message={true}/> but this doesn't work since the props is not being passed.

Is there a way to combine both? Or am I missing some extra steps?

gmwill934
  • 609
  • 1
  • 10
  • 27

1 Answers1

0

The code after history.push('/') is causing error as the isauthenticated is false then user object does not contain those fields and hence the error!

import React from 'react';
import {useAuth0} from '@auth0/auth0-react';

export const Profile = ({history}) => {
  const {user, isAuthenticated} = useAuth0();

  if(!isAuthenticated) {
     history.push('/');
     return
  }

  else{ 
    const {email, picture} = user;

    return (
      <div>
        <h4>Profile</h4>
        <p>{email}</p>
        <p>{picture}</p>
      </div>
    );
  }
}; 

This should work!!

Dhruva-404
  • 168
  • 2
  • 10