Next.js Discord

Discord Forum

Does anyone how to setup Zustand with Nextjs

Unanswered
Atlantic herring posted this in #help-forum
Open in Discord
Atlantic herringOP
Does anyone how to setup Zustand with Nextjs,
I want to store my auth session in zustand, but Imnot sure how to implement this in right way.
Is there any example for this?
Thank you.

12 Replies

@Atlantic herring solved?
Atlantic herringOP
Im following that guides already
"use client";

import { createContext, ReactNode, useContext, useEffect, useState } from "react";
import { useStore } from "zustand";

import { AuthStore, createAuthStore, Session } from "@/stores/auth-store";

export type AuthStoreApi = ReturnType<typeof createAuthStore>;

export const AuthStoreContext = createContext<AuthStoreApi | undefined>(undefined);

export interface CounterStoreProviderProps {
    children: ReactNode;
    inital: Session;
}

export const AuthStoreProvider = ({ children, inital }: CounterStoreProviderProps) => {
    console.log({ inital });
    const [store, setStore] = useState<AuthStoreApi | null>(null);
    useEffect(() => {
        const newStore = createAuthStore();
        if (inital) {
            newStore.getState().setSession(inital);
        }
        setStore(newStore);
    }, [inital]);

    if (!store) return <div></div>;

    return <AuthStoreContext.Provider value={store}>{children}</AuthStoreContext.Provider>;
};

export const useAuthStore = <T,>(selector: (store: AuthStore) => T): T => {
    const authStoreContext = useContext(AuthStoreContext);

    if (!authStoreContext) {
        throw new Error(`useCounterStore must be used within CounterStoreProvider`);
    }

    return useStore(authStoreContext, selector);
};
import { createStore } from "zustand/vanilla";

export interface Session {
    login: boolean;
    session: SessionClass;
}

export interface SessionClass {
    name: string;
    email: string;
    image: string;
    id: string;
    provider: string;
    role: string;
}

export type AuthState = {
    session: Session | null;
};

export type AuthActions = {
    setSession: (session: any) => void;
};

export type AuthStore = AuthState & AuthActions;

export const defaultInitState: AuthState = {
    session: null,
};

export const createAuthStore = (initState: AuthState = defaultInitState) => {
    return createStore<AuthStore>()((set) => ({
        ...initState,
        setSession: (data) => set(() => ({ session: data })),
    }));
};
export default async function RootLayout({
    children,
}: Readonly<{
    children: React.ReactNode;
}>) {
    const auth: Session = await session();
    return (
        <html lang="en">
            <body className={`${geistSans.variable} ${geistMono.variable} antialiased`}>
                <AuthStoreProvider inital={auth}>{children}</AuthStoreProvider>
            </body>
        </html>
    );
}
But is that okay when I change page or reload, the store also get reload the data twice
why is that? or because I put like this?
export const AuthStoreProvider = ({ children, inital }: CounterStoreProviderProps) => {
    console.log({ inital });
    const [store, setStore] = useState<AuthStoreApi | null>(null);
    useEffect(() => {
        const newStore = createAuthStore();
        if (inital) {
            newStore.getState().setSession(inital);
        }
        setStore(newStore);
    }, [inital]);

    if (!store) return <div></div>;

    return <AuthStoreContext.Provider value={store}>{children}</AuthStoreContext.Provider>;
};
@B33fb0n3 lemme know if you know how to do this properly
Atlantic herringOP
Is that normal?
even I disable the strict mode