mardi 18 août 2020

react firebase rendering order or state mutation

i was working with the firebase auth system and i got a problem when the user is login and i update the page, the register form that should be render only if the user isn't login flash for a second i understand that the state takes some times to get update so i tried this at my Index.js

firebase.auth().onAuthStateChanged(function (user) {
  if (user) {
    ReactDOM.render(
      <App />,
      document.getElementById('root')
    );
  } else {
    ReactDOM.render(
      <LoginModal modal={true} />,
      document.getElementById('root')
    );
  }
});

and it was working perfectly until i implement the signup logic that is here

const handleSubmitRegister = (e) => {
        e.preventDefault();
        firebase.auth().createUserWithEmailAndPassword(dataRegister.email, dataRegister.password)
            .then(() => {
                return firebase.auth().currentUser.updateProfile({
                    displayName: dataRegister.name
                })
            }).then(() => console.log("name updated"))
            .catch((err) => console.log(err));
    }

my problem now is that a component inside App need the displayName but this component render before the user is updated so i need to update the page to see the displayname is my page. here is the component

export default function Profile() {
    const [user, setUser] = useState({});
    useEffect(() => {
        setUser(firebase.auth().currentUser)
    }, [])
    console.log(user);
    return (
        <div className="col">
            <button onClick={() => {
                firebase.auth().signOut().then(() => {
                    console.log('logout')
                }).catch(function (error) {
                    console.log('/* An error happened.*/')
                });

            }}>logout</button>
            <h4>
                {user.displayName}
            </h4>
        </div>
    )
}

i used the console.log so as you can see the Profile component render before the user is updated but what is more weird when i open the object i find the displayname updated but it's not render enter image description here enter image description here so i don't know where is the problem, is it like a state mutation ? or did i miss something ? sorry for my bad english




Aucun commentaire:

Enregistrer un commentaire