What is the best practice to fetch initial loading data from a API in React server side rendering? I had tried loading the initial data in the constructor method. But it's not working.
Asked
Active
Viewed 1,641 times
2
-
1Would be great if you add some additional information to your question. Code? Problem? Attempts? Questions without these are usually closed as too broad or simply don't receive any answers. – Boris Zagoruiko May 02 '16 at 11:40
-
Possible duplicate of [Strategies for server-side rendering of asynchronously initialized React.js components](http://stackoverflow.com/questions/25983001/strategies-for-server-side-rendering-of-asynchronously-initialized-react-js-comp) – iofjuupasli May 02 '16 at 12:17
-
1I need to fetch the data from an external API and use that data to render the component. How should i go about it. Should i hit the external api in the constructor method for that purpose. – Nithin M Thomas May 02 '16 at 14:02
1 Answers
0
Look at using redux-saga to help you fetch the initial data on server side.
Below is a snippet from my React example that uses Redux Saga and Hapi for Server-side Rendering
class ReactController {
_html = null;
mapRoutes(server) {
server.route({
method: 'GET',
path: '/{route*}',
handler: async (request, reply) => {
const store = ProviderService.createProviderStore({}, true);
const context = {};
const app = (
<RouterWrapper
store={store}
location={request.path}
context={context}
isServerSide={true}
/>
);
this._html = (this._html === null) ? await this._loadHtmlFile() : this._html;
store.runSaga(rootSaga).done.then(async () => {
const renderedHtml = renderToString(app);
const state = store.getState();
const initialState = {
...state,
renderReducer: {
isServerSide: true,
},
};
const html = this._html
.slice(0)
.replace('{title}', state.metaReducer.title)
.replace('{description}', state.metaReducer.description)
.replace('{content}', renderedHtml)
.replace('{state}', JSON.stringify(initialState));
if (context.url) {
console.info('context', context);
}
reply(html);
});
renderToString(app);
store.endSaga();
},
});
}
async _loadHtmlFile() {
const htmlPath = path.resolve(__dirname, '../../public/index.html');
return fse.readFile(htmlPath, 'utf8');
}
}

codeBelt
- 1,727
- 16
- 22