2

I'm new to React and Firebase and I'm trying get the user object that's populated after sign in/sign up to a new component so I can access it and create a database for each user, however I can't seem to access the this.state.user from another component. Here's my code:

    import React, { Component } from 'react';
import fire from './config/Fire';
import Login from './Login';
import Home from './Home';

class App extends Component {

  constructor(props){
    super(props);
    this.state = {
      user: {},
    }
  }

  // After this component renders, we will call on auth lister which will begin auth listener process
  componentDidMount(){
    this.authListener();
  }

  authListener() {
    fire.auth().onAuthStateChanged((user) => {
      console.log(user);
      if (user) {
        this.setState({ user });
      } else {
        this.setState({ user: null });
      }
    });
  }

  render() {
    return (
      <div className="App">
        {this.state.user ? (<Home user={this.state.user}/>) : (<Login/>)}
      </div>
    );
  }
}

export default App;

and in my new component i have:

componentDidMount(){
    fire.auth().onAuthStateChanged((user) => {
        if (this.props.user){
            console.log(this.props.user);
            // const userId = user.uid;
            // fire.database().ref(`users/${userId}`).set({
            //     username: '',
            //     age: ''
            // });
        } else {
            console.log('No user');
        }
    });
}
Josh Pittman
  • 7,024
  • 7
  • 38
  • 66
juicy j
  • 183
  • 5
  • 20

1 Answers1

0

You are listening for the user in componentDidMount of the App component, then you are passing that data into the home component in <Home user={this.state.user}/>

This means that you can refrence the user object inside the Home component as this.props.user.

You don't need to call the onAuthStateChanged handler again inside Home, you already did that in the App Component.

Hope that helps.

Josh Pittman
  • 7,024
  • 7
  • 38
  • 66