0

I am trying to retrieve the properties of my firebase Auth object. When I print the Auth object in the console I am able to access the "displayName" property but when I pass the Auth object into my component, I keep getting the error "Cannot read property 'displayName' of null". Here is the code below:

class App extends React.Component {
  constructor() {
    super();

    this.state = {
      currentUser: null,
    };
  }

  unsubscribeFromAuth = null;

  componentDidMount() {
    this.unsubscribeFromAuth = auth.onAuthStateChanged((user) => {
      this.setState({ currentUser: user });
      console.log(user.displayName); // I am able to access the property here
    });
  }

  componentWillUnmount() {
    this.unsubscribeFromAuth();
  }

  render() {
    const { currentUser } = this.state;
    console.log(currentUser.displayName); // I am unable to access it here
    return (
      <div className="App">
        <Navbar currentUser={currentUser} />
        <Switch>
          <Route exact path="/" component={HomePage} />
          <Route path="/login" component={LoginPage} />
          <Route path="/signup" component={SignUpPage} />
          <Route path="/shop" component={ShopPage} />
        </Switch>
      </div>
    );
  }
}

export default App;
2
  • I am facing the same issues. Commented Mar 13, 2021 at 17:20
  • @Amiteshmanitiwari has to do with the component lifecycle. put the currentUser in a ternary operator { currentUser ? <Navbar user={currentUser} /> : <LoggedOutNavbar /> } Commented Mar 15, 2021 at 5:55

1 Answer 1

1

The problem is, that the render method is executed, before a user is there.

So the solution is to expect that the current user can be null and make a check in the render method. Example:

{
    currentUser ? <Navbar user={currentUser} /> : <LoggedOutNavbar />
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.