0

I am trying to get userdata from firestore based on uid obtained from authStatechanged in mobx. But when i try to access it in useEffect, it shows value is undefined but if i print its value in body it shows after slight delay. What should i fo to get that value in useeffect.

index.js

 useEffect(() => {
      setposts(props.posts);
    authUser && setuser(authUser) ; //it shows authuser is null
    
    }, []);

  return (
   
 <Layout>
     
 {authUser && authUser.uid}  //it gives correct value after delay

</Layout>


store.js

class Store {

  @observable authUser = null


  constructor(){
       
        const result = firebase.auth().onAuthStateChanged(authUser => { 

        if(authUser){
          this.authUser = authUser
        }
       })
    }
}
Sagar Giri
  • 23
  • 6

1 Answers1

0

firebase.auth() is asynchronous function, so when you component is rendered first time authUser is null. After some time this call gets resolved with user, then onAuthStateChanged is called and you set the user. But your useEffect is already got called and since you specified empty array [] as effect dependency it does not get called again.

You can use second effect like this, for example:

 useEffect(() => {
      authUser && setuser(authUser);
    }, [authUser]);

Every time authUser changes this effect will be called.

But at the same time I am not quite understand why you need to setuser anyway, you can use it right away since it is stored inside your Store.

Danila
  • 15,606
  • 2
  • 35
  • 67