Skip to content

Cannot read property of null when extracting data from state

I’m trying to display a navigation item when a flag is true, but the problem is, when I try to get the following data from it, it returned me undefined, I created the following for that:

let navigate = useNavigate();

  const userSignin = useSelector((state: RootStateOrAny) => state.userSignin);
  const { userInfo } = userSignin;

  const checkAdmin = useCallback(() => {
    if (userInfo) {
      if (typeof userInfo.user === "undefined") {
        return null;
      } else {
        return userInfo.user.isAdmin;
      }
    } else {
      return null;
    }
  }, []);

useEffect(() => {
    checkAdmin();
    if (!userInfo.user.isAdmin) {
      navigate("/");
    }
  }, [checkAdmin]);

I did the checkAdmin function, because before that I had userInfo.user.isAdmin and it returned me undefined.

{checkAdmin() && (
            <NavbarItem
              component='li'
              onMouseEnter={() => setTopMenuIndex(4)}
              onMouseLeave={() => setTopMenuIndex(-1)}
            >
              <Box
                style={{ whiteSpace: "nowrap" }}
                component='a'
                {...{ href: "/createItem" }}
              >
                {topMenuIndex === 4 && <Tippy topMenuIndex={topMenuIndex} />}
                Admin Dashboard
              </Box>
            </NavbarItem>
          )}

Now I want to make sure that if you don’t have that flag, you will get redirected to the homepage, but using the userInfo.user.isAdmin is returning null now. How can I recode this logic to be better or how can I make at least this useEffect work correctly.

Answer

Firstly you are passing checkAdmin in useEffect inside an array, but it is a function. According to my knowledge you can only pass state or props to refresh the component or re-render.

I am not sure what exactly the ask was but, according to me.

let navigate = useNavigate();

const userSignin = useSelector((state: RootStateOrAny) => state.userSignin);
const { userInfo } = userSignin;

// Old Node Version
const checkAdmin = () => {
  if(userInfo) {
    if(userInfo.user) {
      return userInfo.user.isAdmin
    }
  };
  return false;
};

// New Node Version
const checkAdmin = () => {
  if(userInfo?.user?.isAdmin) {
    return userInfo.user.isAdmin
  };
  return false;
};

useEffect(() => {
    if (!checkAdmin()) {
      navigate("/");
    }
  }, [userInfo]);