UNPKG

react-intlayer

Version:

Easily internationalize i18n your React applications with type-safe multilingual content management.

55 lines (53 loc) 1.59 kB
import react from "react"; //#region src/server/serverContext.tsx /** * Creates a new datastore for a given server context. * Attempts to closely mimic the `createContext` API. * * @example * const IntlayerServer = createServerContext<string | null>(null); * * <IntlayerServer value={locale}> * {children} * </IntlayerServer> */ const cacheFallback = () => () => ({ value: void 0 }); const createServerContext = (defaultValue) => { throwInClient(); const getCache = (react.cache ?? cacheFallback)(() => ({ value: void 0 })); const Provider = ({ children, value }) => { getCache().value = value; return children; }; const ServerContext = Provider; ServerContext.Provider = Provider; ServerContext.Consumer = (props) => { const store = getCache(); return props.children(store ? store.value : defaultValue); }; ServerContext._storage = getCache; ServerContext._defaultValue = defaultValue; return ServerContext; }; /** * Fetches a value present in a given server context. * Attempts to closely mimic the `useContext` API. * * @example * getServerContext(IntlayerServer); */ const getServerContext = ({ _storage, _defaultValue }) => { const store = _storage(); if (!store) return _defaultValue; return store.value; }; /** * Throws if called within a client component environment. * Useful to help prevent mistakes. */ const throwInClient = () => { if (typeof window !== "undefined") throw new Error(`createServerContext only works in Server Components`); }; //#endregion export { createServerContext, getServerContext }; //# sourceMappingURL=serverContext.mjs.map