I have an react/next.js application which is using zustand. For context, im trying to create HOC client route guard in next.js.
This is the usage of my zustand store module:
"use client";
import React, {useEffect} from "react";
import {useAuthStore} from "@/store/authStore";
import {useRouter} from "next/navigation";
const ProtectedRoute = <P extends object>(WrappedComponent: React.ComponentType<P>) => {
const ComponentWithAuth = (props: P) => {
const authStore = useAuthStore();
const router = useRouter();
console.log(authStore);
useEffect(() => {
console.log(authStore);
if (!authStore.user) router.push("/");
}, []);
return <WrappedComponent {...props} />;
};
return ComponentWithAuth;
};
export default ProtectedRoute;
And this is the component in which the HOC is used (“/app” page):
"use client"
import isAuth from "@/components/layout/protectedRoute";
const Page = () => {
return <div>App Page</div>
}
export default isAuth(Page);
Now the problem, when i try to access /app through url, directly typing the /app into url bar and hitting enter to navigate authStore is an object of zustand store with all properties etc. When im redirecting to /app page with function bellow which is called on login form submit, the authStore is being undefined on the console.log and later and is crashing application.
const submitForm = async (data: LoginFormValues) => {
try {
await login(data);
const user = await getMe();
authStore.setUserData(user);
router.push("/app");
} catch (e) {}
}
Im just trying to learn react and next js. This approach is what i have found on internet as a solution to client route guard.
I have tried different approaches and before i was calling also refresh with /me requests to figure out if user was logged before. I thought that the async function in the effect was causing that but i was mistaken.