UNPKG

@react-hook/server-promises

Version:

A React hook for continuously rendering a React tree until no promises are pushed to server-promises's context in a given render.

1 lines 2.53 kB
{"version":3,"file":"index.mjs","sources":["../../src/index.tsx"],"sourcesContent":["import * as React from 'react'\nexport const ServerPromisesContext = React.createContext(createPromisesCache())\nexport const useServerPromises = () => React.useContext(ServerPromisesContext)\n\n// renders the app until there are no promises that get pushed to the cache array\nexport function loadPromises<T>(\n tree: React.ReactElement,\n // eslint-disable-next-line @typescript-eslint/no-var-requires\n render: (element: React.ReactElement) => T = require('react-dom/server')\n .renderToStaticMarkup\n): Promise<T> {\n const cache = createPromisesCache()\n\n const process = (): Promise<T> | T => {\n const html = render(\n React.createElement(ServerPromisesContext.Provider, {\n value: cache,\n children: tree,\n })\n )\n\n return cache.promises.length > 0 ? cache.load().then(process) : html\n }\n\n return Promise.resolve().then(process)\n}\n\n// preloads all of the async components used in the current react tree\nfunction createPromisesCache(initial: Promise<any>[] = []) {\n const cache = {\n // Map from Query component instances to pending promises.\n promises: initial,\n push: (...args: Promise<any>[]) => cache.promises.push(...args),\n load(): Promise<any> {\n return Promise.all(cache.promises).then(() => (cache.promises = []))\n },\n }\n\n return cache\n}\n\nexport interface ServerPromisesContextType {\n /**\n * An array of promises that are still pending\n */\n promises: Promise<any>[]\n /**\n * Adds a promise to the promises array\n */\n push: (...args: Promise<any>[]) => number\n /**\n * Loads all of the promises currently in the promises array\n */\n load: () => Promise<any>\n}\n"],"names":["loadPromises","tree","render","require","renderToStaticMarkup","cache","createPromisesCache","process","html","__reactCreateElement__","ServerPromisesContext","Provider","value","children","promises","length","load","then","Promise","resolve","initial","push","all","React","useServerPromises"],"mappings":"AAKO,SAASA,EACdC,EAEAC,YAAAA,IAAAA,EAA6CC,QAAQ,oBAClDC,0BAEGC,EAAQC,IAERC,EAAU,SACRC,EAAON,EACXO,EAAoBC,EAAsBC,SAAU,CAClDC,MAAOP,EACPQ,SAAUZ,YAIPI,EAAMS,SAASC,OAAS,EAAIV,EAAMW,OAAOC,KAAKV,GAAWC,UAG3DU,QAAQC,UAAUF,KAAKV,GAIhC,SAASD,EAAoBc,uBAMwBf,EAAMS,SAAW,YANzCM,IAAAA,EAA0B,QAC/Cf,EAAQ,CAEZS,SAAUM,EACVC,KAAM,kBAA6BhB,EAAMS,SAASO,oBAClDL,KAAI,IACKE,QAAQI,IAAIjB,EAAMS,UAAUG,gBAIhCZ,mFArCIK,EAAwBa,EAAoBjB,KAC5CkB,EAAoB,IAAMD,EAAiBb"}