Skip to content

Latest commit

 

History

History
 
 

server-promises

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

useServerPromises()

Bundlephobia Types Build status NPM Version MIT License

npm i @react-hook/server-promises

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

Quick Start

import React from 'react'
import {renderToString} from 'react-dom/server'
import {useServerPromises, loadPromises} from '@react-hook/server-promises'

let LOADED = false
const App = (props) => {
  const serverPromises = useServerPromises()
  // adds a promise to the server promises cache
  const response = useMemo(() => {
    if (LOADED === false) {
      LOADED = true
      return serverPromises.push(fetch('https://github.com'))
    }
  }, [])

  return <span>Status: {response.status}</span>
}

const ServerRenderer = async (props) => `
  <html>
    <body>
      <div id='⚛️'>
        ${await loadPromises(<App />, renderToString)}
      </div>
    </body>
  </html>
`

API

useServerPromises()

A hook for adding promises to an array of promises you need rendered on the server

ServerPromisesContextType

export interface ServerPromisesContextType {
  /**
   * An array of promises that are still pending
   */
  promises: Promise<any>[]
  /**
   * Adds a promise to the promises array
   */
  push: (...args: Promise<any>[]) => number
  /**
   * Loads all of the promises currently in the promises array
   */
  load: () => Promise<any>
}

loadPromises(tree, render?, cache?)

Continuously re-renders the React tree until there are no promises pending in a given render

Argument Type Default Required? Description
tree React.ReactElement undefined Yes A React tree to render to string
render (element: React.ReactElement) => T ReactDOMServer.renderToStaticMarkup No A server renderer to continuously render the tree with

Returns string

LICENSE

MIT