L. A.
L. A.

Reputation: 23

why isn't return <Redirect to="/" /> running?

How come the return is not running? Is it because it is nested in 2 if statement? I am trying to do in in React, where I am checking the custom claims from Firebase, and if the user is an admin, then it will be redirected to the admin home page. Thanks~!

export default function() {
  const classes = useStyles();
  const { currentUser } = useContext(AuthContext);


    if (currentUser != null) {
      currentUser.getIdTokenResult().then(idTokenResult => {
        if (idTokenResult.claims.adminRole) {
          return <Redirect to="/adminHome" />;
        }
      });
    }

   return ( ... )
}

Upvotes: 0

Views: 58

Answers (2)

Eugene
Eugene

Reputation: 983

<Redirect to="/adminHome" /> can work, but not in your case. Because getIdTokenResultis async operation, and the return in the end of your component will return the result before the async getIdTokenResult operation will be finished. And when getIdTokenResult will complete, it's too late to return something.

To do a redirect, do next:

  1. import history

    import {useHistory} from 'react-router-dom'

  2. Use hook in component

    const history = useHistory()

And replace your code:

return <Redirect to="/adminHome" />;

to next:

history.push('/adminHome')

Upvotes: 2

CodeZombie
CodeZombie

Reputation: 2087

currently, your condition is not passing through. Just modify an if statement.

if (idTokenResult.claims && idTokenResult.claims.adminRole) {
          return <Redirect to="/adminHome" />;
 }

If idTokenResult.claims.adminRole exists in an initial render the you can also try this.props.history.push("/adminHome") return null;.

Upvotes: 0

Related Questions