useSession((s) => s.user) will either return an user object or null. On the index page the name of the user should be shown. The page is wrapped in PrivatePageProvider which will redirect the client if the user object is null. So if the user is null, IndexPage should not even be rendered, instead the provider returns null and redirects. However this is not working and a TypeError gets thrown, because IndexPage tries to access name of null. With react-router this approach works, but not with Next. I know I could just use the optional chaining operator, but I want to assume that user is not null if the page is wrapped in PrivatePageProvider.
function PrivatePageProvider({ children }) {
const user = useSession((s) => s.user);
const router = useRouter();
useEffect(() => {
if (!user) {
router.push('/auth/login');
}
}, [user, router]);
return !user ? null : children;
}
function IndexPage() {
const user = useSession((s) => s.user);
return (
<PrivatePageProvider>
<h1>Hello {user.name}</h1>
</PrivatePageProvider>
);
}
Error:
TypeError: Cannot read properties of null (reading 'name')
Why is this error showing up even though IndexPage does not get rendered? How can I get my approach to work without involving the server side?