Skip to content

Commit

Permalink
feat: store 내부에서 쿠키관리하도록 수정
Browse files Browse the repository at this point in the history
- useShallow를 통해 재렌더링되도록 수정

#140
  • Loading branch information
pipisebastian committed Nov 19, 2024
1 parent 943f086 commit c4106ed
Showing 1 changed file with 50 additions and 15 deletions.
65 changes: 50 additions & 15 deletions client/src/stores/useUserStore.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import { useShallow } from "zustand/shallow";

interface UserStore {
id: string | null;
Expand All @@ -7,31 +9,64 @@ interface UserStore {
actions: {
setUserInfo: (id: string, name: string, accessToken: string) => void;
removeUserInfo: () => void;
getUserInfo: () => { id: string | null; name: string | null; accessToken: string | null };
updateAccessToken: (accessToken: string) => void;
checkAuth: () => boolean;
};
}

const useUserStore = create<UserStore>((set, get) => ({
id: null,
name: null,
accessToken: null,
actions: {
setUserInfo: (id: string, name: string, accessToken: string) =>
set(() => ({ id, name, accessToken })),
removeUserInfo: () => set(() => ({ id: null, name: null, accessToken: null })),
updateAccessToken: (accessToken: string) => set(() => ({ accessToken })),
checkAuth: () => {
const state = get();
return !!(state.id && state.name && state.accessToken);
const useUserStore = create<UserStore>()(
persist(
(set, get) => ({
id: null,
name: null,
accessToken: null,
actions: {
setUserInfo: (id: string, name: string, accessToken: string) =>
set(() => ({ id, name, accessToken })),
removeUserInfo: () => {
set(() => ({ id: null, name: null, accessToken: null }));
sessionStorage.removeItem("nocta-storage");
},
getUserInfo: () => {
const state = get();
return {
id: state.id,
name: state.name,
accessToken: state.accessToken,
};
},
updateAccessToken: (accessToken: string) => set(() => ({ accessToken })),
checkAuth: () => {
const state = get();
return !!(state.id && state.name && state.accessToken);
},
},
}),
{
name: "nocta-storage",
storage: createJSONStorage(() => sessionStorage),
partialize: (state) => ({
id: state.id,
name: state.name,
}),
},
},
}));
),
);

// store 값을 변경하는 부분. 주로 api 코드에서 사용
export const useUserActions = () => useUserStore((state) => state.actions);

// store 값을 사용하는 부분. 주로 component 내부에서 사용
export const useUserInfo = () => useUserStore.getState();
export const useUserInfo = () =>
useUserStore(
// state 바뀜에 따라 재렌더링 되도록
useShallow((state) => ({
id: state.id,
name: state.name,
accessToken: state.accessToken,
})),
);

export const useCheckLogin = () =>
useUserStore((state) => !!(state.id && state.name && state.accessToken));

0 comments on commit c4106ed

Please sign in to comment.