score:0

you are not setting the state correctly. use setstate() to set the new state as you cannot update the state without using setstate() method: https://facebook.github.io/react/docs/react-component.html#setstate

fetch('http://backend', {
  mode: 'cors',
})  
.then(res => res.json())
.then(data => this.setstate({data: data})); 

also, the code you have added is not server-side rendering using react. you use the method reactdomserver.rendertostring() to do server-side rendering: https://facebook.github.io/react/docs/react-dom-server.html#rendertostring

score:0

yes, even if you fix the setstate() problem you will still be rendering the component before the fetch. the problem is indeed that fetch is asynchronous.

to be able to server-side render back-end calls you need to wait until all backend calls have been made, set the props & state for all components and then render them out.

two libraries that will help you with figuring out when things are done are redial (https://github.com/markdalgleish/redial) and redux-promise-counter (https://github.com/bitgenics/redux-promise-counter) if you are using redux. more on that below.

the next problem you want to solve is getting that data to the client and initialize your components from that, so you don't have to redo (all) the request(s) on the client again.

you could do all that manually, but if you are serious about ssr, you should probably go for something like redux. a way to store all your application state in one store. makes it easier to store results, ship it to the client and initialize your store from json.


Related Query

More Query from same tag