Skip to content

Commit

Permalink
✨ feat : zustand persist 추가
Browse files Browse the repository at this point in the history
  • Loading branch information
codefug committed Jul 20, 2024
1 parent 6d26b79 commit 665a2be
Show file tree
Hide file tree
Showing 3 changed files with 17 additions and 13 deletions.
22 changes: 13 additions & 9 deletions src/app/store/index.tsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,25 @@
import { create } from "zustand";
import { create, StateCreator } from "zustand";
import { persist } from "zustand/middleware";

type User = {
accessToken: string;
};

type Store = {
type UserState = {
user: User | null;
login: (accessToken: string) => void;
logout: () => void;
};

export const useStore = create<Store>()((set) => ({
export const useStoreSlice: StateCreator<UserState> = (set) => ({
user: null,
login: (accessToken: string) => {
localStorage.setItem("accessToken", accessToken);
document.cookie = `accessToken=${localStorage.getItem("accessToken")}`;
return set(() => ({ user: { accessToken } }));
},
login: (accessToken: string) => set(() => ({ user: { accessToken } })),
logout: () => set(() => ({ user: null })),
}));
});

const persistedUserStore = persist<UserState>(useStoreSlice, {
name: "user",
getStorage: () => localStorage,
});

export const useUserStore = create(persistedUserStore);
4 changes: 2 additions & 2 deletions src/pages/login/ui/index.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { useStore } from "@/app/store";
import { useUserStore } from "@/app/store";
import { postSignIn } from "@/shared/api/api";
import { zodResolver } from "@hookform/resolvers/zod";
import { FieldValues, useForm } from "react-hook-form";
Expand All @@ -11,7 +11,7 @@ const schema = z.object({
});
// 네트워크 요청을 보내기 전에 형식 검사
export function LoginPage() {
const { login } = useStore();
const { login } = useUserStore();
const navigate = useNavigate();
const {
register,
Expand Down
4 changes: 2 additions & 2 deletions src/widgets/header/ui/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import logoUrl from "/src/shared/asset/headerLogo.png";
import { Link } from "react-router-dom";
import loginUrl from "/src/shared/asset/login.png";
import { Button } from "@/shared/ui/Button";
import { useStore } from "@/app/store";
import { useUserStore } from "@/app/store";

export const Header = () => {
const { user } = useStore();
const { user } = useUserStore();
return (
<header className="header">
<div className="wrapper">
Expand Down

0 comments on commit 665a2be

Please sign in to comment.