'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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
