React Use API
  • Introduction
  • Usage
    • Getting Started
    • Advanced Usage
      • List API and Pagination
      • Request Control
      • Data Processing
      • Side-Effect Dependencies
      • Watch option
    • TypeScript
  • API
    • useApi
    • State
    • Request Function
    • ApiProvider
    • injectSSRHtml
    • loadApiCache
  • Server Side Rendering
    • SSR Settings
    • Examples
      • Real World Examples
      • With Ant Design
Powered by GitBook
On this page

Was this helpful?

  1. Server Side Rendering

SSR Settings

react-use-api guarantees that the SSR for each HTTP request is thread-safe as long as passing the api context with SSR settings to ApiProvider.

SSR and injecting the cached api data

server/render.js
// server/render.js (based on Express framework)
import React from 'react'
import ReactDom from 'react-dom'
import { StaticRouter } from 'react-router-dom'
import { ApiProvider, injectSSRHtml } from 'react-use-api'

import App from '../../src/App'

export const render = async (req, axios) => {
  const { url } = req
  const apiContext = {
    settings: {
      axios, // your custom axios instance
      isSSR: () => true // we are 100% sure here is SSR mode
    }
  }
  const routerContext = {}
  const renderSSR = () =>
    ReactDom.renderToString(
      <ApiProvider context={apiContext}>
        <StaticRouter location={url} context={routerContext}>
          <App />
        </StaticRouter>
      </ApiProvider>
    )
  const html = await injectSSRHtml(apiContext, renderSSR)
  return html
}

The cache data is inserted into the html text as well.

The cache data will be cleaned up after calling loadApiCache() by default

<script>
  window.__USE_API_CACHE__ = '[{ ... }]' // the cache data
</script>
PreviousloadApiCacheNextExamples

Last updated 5 years ago

Was this helpful?