UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

28 lines (27 loc) 1.17 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { createContext, use } from "react"; import { APICache } from "../api/index.js"; import { RequiredError } from "../error/RequiredError.js"; import { useInstance } from "./useInstance.js"; import { useStore } from "./useStore.js"; /** * Create an API context. * - Allows React elements to call `useAPI()` to access endpoint stores in an API provider. * - Each mounted `APIContext` gets its own in-memory store cache. * * @todo Use and integreate our `EndpointCache` functionality and use it in this. */ export function createAPIContext(provider) { const CacheContext = createContext(undefined); function useAPI(endpoint, payload) { const cache = use(CacheContext); if (!cache) throw new RequiredError(`useAPI() can only be used inside <APIContext>`, { caller: useAPI }); return useStore(endpoint ? cache.get(endpoint).get(payload) : undefined); } function APIContext({ children }) { const cache = useInstance(APICache, provider); return _jsx(CacheContext, { value: cache, children: children }); } return { useAPI, APIContext }; }