React component not rendering after user authentication

Viewed 157

After I signup a user and dispatch the user value to my global store, I try to render my dashboard component. However, my dashboard component does not render although I have my user value set.

(When I console log, the user is definitely set)

Here is where I set the user:

function App() {
  const [{ user }, dispatch] = useStateValue();
  useEffect(() => {
    // will only run once when the app component loads...

    auth.onAuthStateChanged((authUser) => {
      console.log("THE USER IS >>> ", authUser);

      if (authUser) {
        // the user just logged in / the user was logged in

        dispatch({
          type: "SET_USER",
          user: authUser.displayName,
        });
      } else {
        // the user is logged out
        dispatch({
          type: "SET_USER",
          user: null,
        });
      }
    });
  }, []);

And here is the code that renders the component:

  <Route
          path="/dashboard"
          render={() =>
            user ? (
              <DashboardLayout>
                <Dashboard />
              </DashboardLayout>
            ) : (
              <h2>No user</h2>
            )
          }
        />

Now, when I run this code on my localhost, the NO USER flashes and then disappears. Any ideas why?

Here is the code for my DashboardLayout:

const DashboardLayout = (props) => {
  return (
    <div>
      <Header {...props} />
      <div className="main">{props.children}</div>
    </div>
  );
};

And here is the code for my dashboard:

function index() {
  return (
    <div className="dashboard">
      <div className="dash__left">
        <Sidebar />
      </div>
      <div className="dash__middle">
        <LinkButtonTypes />
        <ContentContainer />
      </div>
      <div className="dash__right">
        <PersonalUrl />
        <PhoneMockup />
      </div>
    </div>
  );
}

export default index;
1 Answers

With the way the useEffect as defined above, it will trigger the re-render of React only when setting the initial value due to the empty array as the second argument, so you wouldn't see any changes on the DOM since render wouldn't be triggered. You might want to change the second argument of useEffect to apply the re-render each time the user state is changed, so instead of an empty array, use [user] I haven't tried it myself but that will be a good direction to explore.

Related