Gatsby initial rerender on client side bug

≡放荡痞女 提交于 2020-03-25 18:48:47

问题


So, I have been investigating this bug for a while now and I think I got to the root cause of it. I have a navbar that changes if the user is logged in or not. On server render (I am using gatsby), this property is obviously always false meaning that I will get the guest navbar from the server on initial render.

I have the following hook for checking isLoggedIn:

import { useContext, useState, useEffect } from 'react';
import { UserContext } from '../contexts/UserContext';
import { isAuthenticated } from '../services/pilates-studio/localstorage';

const useIsLoggedIn = () => {
  const { user } = useContext(UserContext);
  const [isLoggedIn, setIsLoggedIn] = useState(isAuthenticated);

  useEffect(() => {
    console.log('we update isLoggedIn');
    setIsLoggedIn(!!user || isAuthenticated);
  }, [user]);
  return isLoggedIn;
};

export default useIsLoggedIn;

isAuthenticated retrieves the access token from the localStorage, so as soon as we hydrate the application on the client, and the user is already logged in, isAuthenticated will result to true.

So the first state of isLoggedIn on the client side will be true. So we get the guest navbar form the server but since there is no state change ever, we are not rerendering the navbar even so technically the navbar state isLoggedIn has changed.

My navbar:

const NavBarContainer = () => {
  const isLoggedIn = useIsLoggedIn();

  return (
    <NavBar logo={Logo} menu={NavMenu} isMenuOpen={isMenuOpen}>
      <NavBarItem key="courses" label="Kurse" link={isLoggedIn ? '/courses' : '/courses/starter'} />
      <NavBarItem key="appointment" label="Termine" link="/appointment" show={isLoggedIn} />
      <NavBarItem key="trainers" label="Trainer" link="/trainers" />
      <NavBarItem key="login" label="Login" link="/login" show={!isLoggedIn} floatRight />
      <NavMenuButton key="menu" label="Menu" onClick={handleMenuClicked} icon={<UserIcon />} show={isLoggedIn} floatRight />
    </NavBar>
  );
};

export default NavBarContainer;

If I change the initial state of my hook to

const [isLoggedIn, setIsLoggedIn] = useState(false);

I get it to rerender but now I have a navbar that "blinks"/"flickers" on inital loading since it rerenders from guest to logged in navbar in a second. I would like to avoid that flickering.

I am quite new to SSR and gatsby. How would you solve the flickering? How can I have the inital state of isLoggedIn being set to true and still force a rerender?

Thanks for the support.

来源:https://stackoverflow.com/questions/60592022/gatsby-initial-rerender-on-client-side-bug

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!