Home > Software design >  How do I use hooks to rerender after a condition has changed?
How do I use hooks to rerender after a condition has changed?

Time:10-17

I have a page where i want it to show one component if a user is logged in, if not logged in, it shows the login component.

I am trying to make it such that after login, test the same condition and automatically change state to the component that requires authentication.

Right now I have it where, it shows me the login page. After I login if I click refresh, it still stays on the login page, but if I go to another page, and come back, it works. How do I make it always check if logged in?

I am trying to use hook useEffect, but I am not achieving this.

The solution doesn't have to be hooks, could be anything, I just thought maybe hooks was the way to solve this issue.

const Properties = () => {
  const [user, setUser] = useState();

  console.log(user);

  useEffect(() => {
    setUser(auth.currentUser);
  }, [auth.currentUser]);

  return (
    <>
      <Head>
        <title>Add Property</title>
        <meta name="keywords" content="web dev" />
      </Head>
      <h1>Add Property</h1>
      <p>Welcome to the add Property new</p>

      {user ? <AddProperty /> : <Login />}
    </>
  );
};

export default Properties;

Here is the login component (i excluded the jsx and unnecessary bits).

onSubmit: (values) => {
  console.log("onSubmit", values);
  signInWithEmailAndPassword(auth, values.email, values.password)
    .then((userCredential) => {
      const user = userCredential.user;
      console.log("user logger in");
    })
    .catch((error) => {
      const errorCode = error.code;
      const errorMessage = error.message;
    });
  },
});

CodePudding user response:

It doesn't work that way. Your code has to listen on the auth state change event onAuthStateChanged from firebase, not its user object.

const Properties = () => {
  const [user, setUser] = useState();

  console.log(user);

  useEffect(() => {
    // you might export this as a service or something similarly.
    const unsubscribe = firebase.auth().onAuthStateChanged((user) => {
      setUser(user);
    });
    return unsubscribe;
  }, []);

  return (
    <>
      <Head>
        <title>Add Property</title>
        <meta name='keywords' content='web dev' />
      </Head>
      <h1>Add Property</h1>
      <p>Welcome to the add Property new</p>

      {user ? <AddProperty /> : <Login />}
    </>
  );
};

export default Properties;
  • Related