UNPKG

@ai-growth/nextjs

Version:

Seamlessly integrate Sanity CMS with Next.js applications for automated blog routing and rendering

33 lines (32 loc) 1.21 kB
import { jsx as _jsx } from "react/jsx-runtime"; import { createContext, useContext, useCallback, useState } from 'react'; import { CacheManager, defaultCacheManager } from '../utils/cache-manager'; const CacheContext = createContext(null); export const CacheProvider = ({ config, enabled = true, children, }) => { const [cacheManager] = useState(() => { return config ? new CacheManager(config) : defaultCacheManager; }); const [metrics, setMetrics] = useState(() => cacheManager.getMetrics()); const refreshMetrics = useCallback(() => { setMetrics(cacheManager.getMetrics()); }, [cacheManager]); const clearCache = useCallback(async () => { await cacheManager.clear(); refreshMetrics(); }, [cacheManager, refreshMetrics]); const contextValue = { cacheManager, metrics, enabled, refreshMetrics, clearCache, }; return (_jsx(CacheContext.Provider, { value: contextValue, children: children })); }; export function useCache() { const context = useContext(CacheContext); if (!context) { throw new Error('useCache must be used within a CacheProvider'); } return context; }