getDataFromTree()

getDataFromTree()

Params

  • tree: React.ReactElement

This function return a Promise that will resolve to a string, containing the static markup for the React app. Most of the time, you are not going to use the static markup generated by this function for your response. The main purpose of this function is to resolve all the data inside your App tree, so you can start rendering your App tree with whatever methods you want, be it ReactDOM.renderToString(), ReactDOM.renderToNodeStream(), or other implementation of React server renderer.

Usage

This is an example of getDataFromTree() before doing React.renderToString(). Note that the output of this code will be exactly the same as calling renderToStringWithData() directly. In practice you can replace React.renderToString() with whatever React server renderer you want, for example React.renderToNodeStream().

Following is an example of SSR implementation using express web server.

import React from 'react';
import ReactDOM from 'react-dom';
import { renderToString } from 'react-dom/server';
import express from 'express';
import { DataProvider, createDataClient } from 'react-isomorphic-data';
import { getDataFromTree } from 'react-isomorphic-data/ssr';
import fetch from 'node-fetch';
import App from './App';
// react-isomorphic-data needs fetch to be available in the global scope
global.fetch = fetch;
const server = express();
server.get('/*', async (req, res) => {
const dataClient = createDataClient({
initialCache: {},
ssr: true, // set this to true on server side
});
const tree = (
<DataProvider client={dataClient}>
<App />
</DataProvider>
);
let markup;
try {
await getDataFromTree(tree);
markup = renderToString(tree);
} catch (err) {
console.error('An error happened during server side rendering!');
}
res.send(`
<html>
<body>
<div id="root">${markup}</div>
</body>
</html>
`);
});
Last updated on 5/8/2020 by Jacky Efendi