QuickTaste.tsx
1,270 bytes
| 1 | import { createContext, useContext, useMemo, useState, type ReactNode } from "react"; |
|---|---|
| 2 | import type { Dish, Tasting } from "../types"; |
| 3 | import { TasteModal } from "./TasteModal"; |
| 4 | |
| 5 | export interface TastePayload { |
| 6 | dish?: Dish; |
| 7 | tasting?: Tasting; |
| 8 | } |
| 9 | |
| 10 | interface QuickTasteContextValue { |
| 11 | openTaste: (payload?: TastePayload) => void; |
| 12 | closeTaste: () => void; |
| 13 | } |
| 14 | |
| 15 | const QuickTasteContext = createContext<QuickTasteContextValue | null>(null); |
| 16 | |
| 17 | export function QuickTasteProvider({ children }: { children: ReactNode }) { |
| 18 | const [payload, setPayload] = useState<TastePayload | null>(null); |
| 19 | const value = useMemo(() => ({ |
| 20 | openTaste: (next: TastePayload = {}) => setPayload(next), |
| 21 | closeTaste: () => setPayload(null) |
| 22 | }), []); |
| 23 | |
| 24 | return ( |
| 25 | <QuickTasteContext.Provider value={value}> |
| 26 | {children} |
| 27 | {payload && ( |
| 28 | <TasteModal |
| 29 | key={payload.tasting?.id ?? payload.dish?.slug ?? "new"} |
| 30 | payload={payload} |
| 31 | onClose={() => setPayload(null)} |
| 32 | /> |
| 33 | )} |
| 34 | </QuickTasteContext.Provider> |
| 35 | ); |
| 36 | } |
| 37 | |
| 38 | export function useQuickTaste(): QuickTasteContextValue { |
| 39 | const context = useContext(QuickTasteContext); |
| 40 | if (!context) { |
| 41 | throw new Error("useQuickTaste must be used inside QuickTasteProvider"); |
| 42 | } |
| 43 | return context; |
| 44 | } |
| 45 | |