I'm currently working on creating a wrapper function that can be used in every dashboard component.
"use client";
const UserWrapper = ({ children }) => {
const user = JSON.parse(window.localStorage.getItem("ysg_u"));
return (
<div>
{user?.token ? (
children
) : (
<div className="min-h-screen flex flex-col justify-center items-center">
<TbFaceIdError className=" w-8 h-8 mb-2" />
<p className="font-headliner text-3xl tracking-wider">ACCESS DENIED</p>
<p className="text-xl -mt-2 font-teko">
Please{" "}
<Link href={"/login"} className="text-orange-700 underline">
Login
</Link>{" "}
First
</p>
</div>
)}
</div>
);
};
export default UserWrapper;
Removed all the imports for long code. The error is showing but the function works. However, I am having trouble completing the build command in Vercel:
event compiled client and server successfully in 729 ms (2087 modules)
- error src/components/Wrapper/user.wrapper.js (11:26) @ window
- error ReferenceError: window is not defined
at UserWrapper (./src/components/Wrapper/user.wrapper.js:22:29)
9 |
10 | const UserWrapper = ({ children }) => {
> 11 | const user = JSON.parse(window.localStorage.getItem("ysg_u"));
| ^
12 |
13 | // useEffect(() => {
14 | // if (!user?.admin) {
- warn The server is running out of memory, restarting to free up memory.
- wait compiling...
- event compiled client and server successfully in 468 ms (2087 modules)
Although I'm using the use client
tag, I'm puzzled as to why it keeps indicating that either window
or localStorage
is undefined.
If I utilize the useEffect
and useState
hooks solution, it will work. The issue lies in the fact that with every route change, the screen momentarily displays no user data before loading the page because useState
takes a few milliseconds to load the localStorage
into state initially.
Does anyone have a proper solution to this problem? I'm using Next.js 13.
Thank you ❤️