ApiProvider

Code

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

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

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

Settings (ReactUseApi.CustomSettings) Options

Each property is optional

Name

Type

Default

Description

cache

LRU

new LRU()

The cache instance based on lru-cache

axios

AxiosStatic | AxiosInstance

axios

axios instance (http client)

maxRequests

number

50

The maximum of API requests when SSR

autoPurgeCache

boolean

true

Cache data will be cleaned up after executing loadApiCache()

useCacheData

boolean

true

Set true to inject JS cache data into html when calling injectSSRHtml()

renderSSR

Function

() => ''

A callback to render SSR string for injectSSRHtml()

isSSR

Function

() => typeof window === 'undefined'

A function to determine if the current environment is server

shouldUseApiCache

Function

(config?: ReactUseApi.Config, cacheKey?: string): boolean

Returns true to enable useApi to get the API data from API cache, which is loaded by loadApiCache. Default is true

debug

boolean

true

Set true to get debug message from console

clientCacheVar

string

'USE_API_CACHE'

The JS variable name of cache data

Last updated