Add "Persisting store data" documentation in "Setup with Next.js" page. #2476
-
Thanks for the great library. I am starting a new project. After reading about zustand, I decided to try it out. I am reading the setup with nextjs documentation and it is working in my application. Now I wanted the state to |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
@shareef99 sure, that's an awesome suggestion. Let me take care of it. |
Beta Was this translation helpful? Give feedback.
-
Hey, I discarded the // store/auth.tsx
import { createJSONStorage, persist } from "zustand/middleware";
import { create } from "zustand";
import { localStorageKeys } from "@/constants/local-storage";
export type AuthUser = {
name: string;
email: string;
};
type AuthState = { auth: AuthUser | null };
type AuthAction = {
login: (_auth: AuthUser) => void;
logout: () => void;
};
export type AuthStore = AuthState & AuthAction;
export const useAuthStore = create<AuthStore>()(
persist(
(set) => ({
auth: null,
login: (auth) => set({ auth: auth }),
logout: () => set({ auth: null }),
}),
{
name: localStorageKeys.authUser,
storage: createJSONStorage(() => localStorage),
}
)
); // store/index.ts
import { useState, useEffect } from "react";
const useStore = <T, F>(
store: (_callback: (_state: T) => unknown) => unknown,
callback: (_state: T) => F
) => {
const result = store(callback) as F;
const [data, setData] = useState<F>();
useEffect(() => {
setData(result);
}, [result]);
return data;
};
export default useStore; // app/auth/page.tsx
import { AuthUser, useAuthStore } from "@/store/auth";
import useStore from "@/store";
export default function Page() {
const router = useRouter();
const authStore = useStore(useAuthStore, (state) => state);
const submitHandler = () => {
// Login Logic
// When I try to do `authStore.login(user)`
// TS says `login` can be `undefined`
}
return (
...
)
} |
Beta Was this translation helpful? Give feedback.
@shareef99 sure, that's an awesome suggestion. Let me take care of it.