UNPKG

shelving

Version:

Toolkit for using data in JavaScript.

34 lines (33 loc) 1.49 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { createContext, use } from "react"; import { DBCache } from "../db/cache/DBCache.js"; import { RequiredError } from "../error/RequiredError.js"; import { useInstance } from "./useInstance.js"; import { useStore } from "./useStore.js"; /** * Create a data context * - Allows React elements to call `useItem()` and `useQuery()` to access items/queries in a database provider. * - If the database has a `CacheDBProvider` in its chain then in-memory data will be used in the returned stores. */ export function createDBContext(provider) { const CacheContext = createContext(undefined); function useItem(collection, // id) { const cache = use(CacheContext); if (!cache) throw new RequiredError("useItem() can only be used inside <DBContext>", { caller: useItem }); return useStore(collection && id ? cache.getItem(collection, id) : undefined); } function useQuery(collection, // query) { const cache = use(CacheContext); if (!cache) throw new RequiredError("useQuery() can only be used inside <DBContext>", { caller: useQuery }); return useStore(collection && query ? cache.getQuery(collection, query) : undefined); } function DBContext({ children }) { const cache = useInstance(DBCache, provider); return _jsx(CacheContext, { value: cache, children: children }); } return { useItem, useQuery, DBContext }; }