SMALL
1. 페이지 정보를 로컬스토리지에 저장하려고 하는데 라우팅을 사용하지않고 좌우 컴포넌트를 별개로 두고 zustand 에 저장값을 넣어서 적용시킴
import {create} from 'zustand';
type Store = {
leftComponent: string | null;
rightComponent: string | null;
activeButton: string | null;
setLeftComponent: (name: string) => void;
setRightComponent: (name: string) => void;
setActiveButton: (name: string) => void;
};
export const usePageStore = create<Store>((set) => ({
leftComponent: null,
rightComponent: null,
activeButton: null,
setLeftComponent: (name) => set(() => ({ leftComponent: name })),
setRightComponent: (name) => set(() => ({ rightComponent: name })),
setActiveButton: (name) => set(() => ({ activeButton: name })),
}));
2. 여기서 zustand에서 저장하는 값을 바로 localStorage에 업데이트함
3. 로컬스토리지에 값이 있으면 그 값을 불러오고 값이 없으면 빈객체를 가져옴
import { create } from 'zustand';
// 스토어 타입 정의
type Store = {
leftComponent: string | null;
rightComponent: string | null;
activeButton: string | null;
setLeftComponent: (name: string) => void;
setRightComponent: (name: string) => void;
setActiveButton: (name: string) => void;
};
// 로컬 스토리지 키 이름 정의
const STORE_KEY = 'page';
// 로컬 스토리지에서 스토어 상태 로드
function loadFromLocalStorage() {
const savedState = localStorage.getItem(STORE_KEY);
return savedState ? JSON.parse(savedState) : {};
}
// 스토어 생성 및 초기 상태 설정
export const usePageStore = create<Store>((set) => ({
...loadFromLocalStorage(), // 로컬 스토리지에서 로드한 상태로 초기화
setLeftComponent: (name) => set(() => ({ leftComponent: name })),
setRightComponent: (name) => set(() => ({ rightComponent: name })),
setActiveButton: (name) => set(() => ({ activeButton: name })),
}));
// 스토어 상태 변경 시 로컬 스토리지에 저장
usePageStore.subscribe((state) => {
localStorage.setItem(STORE_KEY, JSON.stringify(state));
});
LIST
'일반' 카테고리의 다른 글
fetch를 위해 알아본 자료들 (0) | 2024.04.02 |
---|---|
새 글 정보 알람 기능 (0) | 2024.03.22 |
modal dialog component만들기 (0) | 2024.03.20 |
필터기능 구현 (0) | 2024.03.18 |
자료구조 변경 비교 (0) | 2024.03.13 |