1

I'm sorry if my question has already asked. I am a beginner on react and I really want to learn how to do this and understand. I use Firebase on my React.JS project and i want switch a part of header when the user has connected or not.

I think using the conditional-rendering but on the firebase function after the (if) does not allow me to do setState().. or i have an error

So I would be very happy if we could help me or give me a track of where to look for the answers !

class Header extends Component {

state={
  connected: null
}

render(){

  firebase.auth().onAuthStateChanged(function(user) {
    if (user) {


    } else {


    }
  });

  return (


<div className="backgroundheader">

<div className="liensheader">
  <a href="/" className="lili" style={{textDecoration: "none"}}>Home</a>
  <a href="/event" className="lili" style={{textDecoration: "none"}}>Manifestations</a>
  <a href="/commerces" className="lili" style={{textDecoration: "none"}}>Commerces</a>
  <a href="/tips" className="lili" style={{textDecoration: "none"}}>Tips</a>
</div>

{/* options header when the user is disconnect */}
{/* <Deader /> */}

{/* options header when the user is connected */}
{/* <Ceader /> */}

</div>
  );
  }
};
export default Header;

Thank's you and sorry for my bad english :/

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
RudyPley
  • 11
  • 3

1 Answers1

0

The onAuthStateChanged fires asynchronously, so you can't directly use it inside your render method. Whenever you have a situation like this, the solution is to put the asynchronous value into the state, and then use the state in the render method.

So something like:

class Header extends Component {
  state={
    connected: null
  }
  componentDidMount() {
    firebase.auth().onAuthStateChanged(function(user) {
      setState({ user: user });
    });    
  }
  render(){
    return (
<div className="backgroundheader">

<div className="liensheader">
  <a href="/" className="lili" style={{textDecoration: "none"}}>Home</a>
  <a href="/event" className="lili" style={{textDecoration: "none"}}>Manifestations</a>
  <a href="/commerces" className="lili" style={{textDecoration: "none"}}>Commerces</a>
  <a href="/tips" className="lili" style={{textDecoration: "none"}}>Tips</a>
</div>
{ user ? <Deader /> : <Ceader /> }
</div>
  );
  }
};
export default Header;

Also see:

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thank you very much for the reply! I applied all of this to my code and it works! I will take this opportunity to better understand how it works and to look at the links you sent me. Thanks again, have a nice day! – RudyPley Apr 25 '20 at 14:32