|
| 1 | +import * as React from 'react'; |
| 2 | +import { createContext, useContext, useRef } from 'react'; |
| 3 | +import { createStore, StateCreator, StoreApi, useStore } from 'zustand'; |
| 4 | +import { Task } from './types'; |
| 5 | + |
| 6 | +export interface TasksState { |
| 7 | + tasks: Task[]; |
| 8 | + addTask: (task: Task) => void; |
| 9 | + deleteTask: (id: string) => void; |
| 10 | + toggleTask: (id: string) => void; |
| 11 | + clearCompleted: () => void; |
| 12 | +} |
| 13 | + |
| 14 | +export const tasksStoreCreator: StateCreator<TasksState> = (set) => ({ |
| 15 | + tasks: [], |
| 16 | + addTask: (task: Task) => { |
| 17 | + set((state) => ({ tasks: [...state.tasks, task] })); |
| 18 | + }, |
| 19 | + deleteTask: (id: string) => { |
| 20 | + set((state) => ({ tasks: state.tasks.filter((todo) => todo.id !== id) })); |
| 21 | + }, |
| 22 | + toggleTask: (id: string) => { |
| 23 | + set((state) => ({ |
| 24 | + tasks: state.tasks.map((task) => |
| 25 | + task.id === id ? { ...task, completed: !task.completed } : task, |
| 26 | + ), |
| 27 | + })); |
| 28 | + }, |
| 29 | + clearCompleted: () => { |
| 30 | + set((state) => ({ tasks: state.tasks.filter((task) => !task.completed) })); |
| 31 | + }, |
| 32 | +}); |
| 33 | + |
| 34 | +// Use store with context |
| 35 | +// See: https://docs.pmnd.rs/zustand/guides/testing#testing-components |
| 36 | + |
| 37 | +export type TasksStoreApi = StoreApi<TasksState>; |
| 38 | + |
| 39 | +const TasksStoreContext = createContext<TasksStoreApi | undefined>(undefined); |
| 40 | + |
| 41 | +export interface TasksStoreProviderProps extends React.PropsWithChildren { |
| 42 | + // Optionally pass a pre-created store (for testing) |
| 43 | + store?: TasksStoreApi; |
| 44 | +} |
| 45 | + |
| 46 | +export function TasksStoreProvider({ store, children }: TasksStoreProviderProps) { |
| 47 | + const storeRef = useRef<TasksStoreApi>(); |
| 48 | + if (!storeRef.current) { |
| 49 | + // Inject passed store or create a new one |
| 50 | + storeRef.current = store ?? createStore(tasksStoreCreator); |
| 51 | + } |
| 52 | + |
| 53 | + return ( |
| 54 | + <TasksStoreContext.Provider value={storeRef.current}>{children}</TasksStoreContext.Provider> |
| 55 | + ); |
| 56 | +} |
| 57 | + |
| 58 | +export type UseTasksStoreContextSelector<T> = (store: TasksState) => T; |
| 59 | + |
| 60 | +export function useTasksStore<T>(selector: UseTasksStoreContextSelector<T>) { |
| 61 | + const store = useContext(TasksStoreContext); |
| 62 | + if (!store) { |
| 63 | + throw new Error('useTasksStore must be used within TasksStoreProvider'); |
| 64 | + } |
| 65 | + |
| 66 | + return useStore(store, selector); |
| 67 | +} |
0 commit comments