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 (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>