UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

23 lines (22 loc) 898 B
import { jsx as _jsx } from "react/jsx-runtime"; import { createContext, useContext } from "react"; import { UnexpectedError } from "../error/UnexpectedError.js"; import { useMap } from "./useMap.js"; /** * Create a cache context that can be provided to React elements and allows them to call `useCache()` * - Cache is a `Map` indexed by strings that can be used to store any value. */ export function createCacheContext() { const Context = createContext(undefined); const useCache = () => { const cache = useContext(Context); if (!cache) throw new UnexpectedError("useCache() must be used inside <CacheContext>", { caller: useCache }); return cache; }; const CacheContext = ({ children }) => { const cache = useMap(); return _jsx(Context, { value: cache, children: children }); }; return { useCache, CacheContext }; }