Ошибка возникает в компоненте Dashboardlayout , который использует usingInitializeauth для инициализации состояния аутентификации через zustand hore.
Код: Выделить всё
Call Stack
finishRenderingHooks
.next\static\chunks\node_modules_next_dist_compiled_2ce9398a._.js (6231:41)
renderWithHooks
.next\static\chunks\node_modules_next_dist_compiled_2ce9398a._.js (6212:9)
updateFunctionComponent
.next\static\chunks\node_modules_next_dist_compiled_2ce9398a._.js (7543:21)
...
DashboardLayout
.next\static\chunks\_728302a6._.js (2983:223)
ClientSegmentRoot
.next\static\chunks\node_modules_next_dist_1a6ee436._.js (2116:50)
Компонент dashboardlayout:
Код: Выделить всё
// src/layouts/DashboardLayout.tsx
"use client";
import "../globals.css";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import { TaskAppSidebar } from "@/components/layouts/Sidebar/TaskAppSidebar";
import DashboardHeader from "@/components/layouts/Header/DashboardHeader";
import { LayoutWrapper } from "@/components/layouts/LayoutWrapper";
import { usePathname } from "next/navigation";
import { useInitializeAuth } from "@/hooks/useInitializeAuth";
export default function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {
useInitializeAuth();
const pathname = usePathname();
// Add base paths for no-padding
const noPaddingPatterns = [/^\/dashboard\/tasks\/[^\/]+\/comments$/];
const noPadding = noPaddingPatterns.some((pattern) => pattern.test(pathname));
return (
className={`font-inter bg-gray-50 dark:bg-slate-900 text-gray-900 dark:text-gray-100 `}
>
{children}
);
}
Код: Выделить всё
// src/hooks/useInitializeAuth.ts
"use client";
import { useEffect } from "react";
import { useAuthStore } from "@/lib/stores/authStore";
export const useInitializeAuth = () => {
const initializeAuth = useAuthStore((state) => state.initializeAuth);
useEffect(() => {
initializeAuth();
}, [initializeAuth]);
};
Код: Выделить всё
// lib/stores/authStore.ts
import { create } from "zustand";
import { devtools } from "zustand/middleware";
import { authService } from "@/lib/auth/auth.service";
import {
AuthState,
AuthActions,
LoginRequest,
User,
} from "@/lib/auth/auth.types";
interface AuthStore extends AuthState, AuthActions {}
const USER_KEY = "taskapp-user";
const TOKEN_KEY = "taskapp-token";
const createInitializeAuth = (set: any) => () => {
const userString = localStorage.getItem(USER_KEY);
const token = localStorage.getItem(TOKEN_KEY);
if (userString && token) {
try {
const user: User = JSON.parse(userString);
set({
user,
token,
isAuthenticated: true,
isLoading: false,
});
} catch (err) {
console.error("Failed to parse stored user:", err);
localStorage.removeItem(USER_KEY);
localStorage.removeItem(TOKEN_KEY);
set({
user: null,
token: null,
isAuthenticated: false,
isLoading: false,
});
}
} else {
set({
user: null,
token: null,
isAuthenticated: false,
isLoading: false,
});
}
};
export const useAuthStore = create()(
devtools(
(set, get) => ({
user: null,
token: null,
isAuthenticated: false,
isLoading: false,
// ... other methods
initializeAuth: createInitializeAuth(set),
}),
{ name: "auth-store" }
)
);
Код: Выделить всё
// src/layouts/DashboardLayout.tsx
"use client";
import "../globals.css";
import { SidebarInset, SidebarProvider } from "@/components/ui/sidebar";
import { TaskAppSidebar } from "@/components/layouts/Sidebar/TaskAppSidebar";
import DashboardHeader from "@/components/layouts/Header/DashboardHeader";
import { LayoutWrapper } from "@/components/layouts/LayoutWrapper";
import { usePathname } from "next/navigation";
import { useInitializeAuth } from "@/hooks/useInitializeAuth";
import { useEffect, useState } from "react";
import { useAuthStore } from "@/lib/stores/authStore";
import { TaskAppLoader } from "@/components/TaskAppLoader";
export default function DashboardLayout({
children,
}: {
children: React.ReactNode;
}) {[enter image description here][1]
const [isInitialized, setIsInitialized] = useState(false);
const pathname = usePathname();
const initializeAuth = useAuthStore((state) => state.initializeAuth);
useEffect(() => {
// Initialize auth only on client side after component mounts
try {
initializeAuth();
setIsInitialized(true);
} catch (error) {
console.error("Failed to initialize auth:", error);
}
}, [initializeAuth]);
// Add base paths for no-padding
const noPaddingPatterns = [/^\/dashboard\/tasks\/[^\/]+\/comments$/];
const noPadding = noPaddingPatterns.some((pattern) => pattern.test(pathname));
// Show loading state while initializing
if (!isInitialized) {
return (
);
}
return (
className={`font-inter bg-gray-50 dark:bg-slate-900 text-gray-900 dark:text-gray-100 `}
>
{children}
);
}
основная причина
Ошибка »сделала меньше крючков, чем ожидалось,« возникает, когда реагирует
< /ol>
Почему это разрешает ошибку < /h3>
предотвращает несоответствия крючков < /strong>: раннее возвращение обеспечивает дочерние компоненты (которые могут использовать крючки), до тех пор, пока штат не станет стабильным. Инициализация на стороне клиента явно управляется, избегая проблем с гидратацией.
поддерживает порядок крюка : контролируя, когда полные компоненты дерева, выполнение крюка остается последовательным в разных рендеров. Next.js Hooks Zustand ssr гидратация
Подробнее здесь: https://stackoverflow.com/questions/797 ... cidental-e