-1

I'm really don't understand how we can fetch data from DB in universal (isomorphic) server-side rendering react application. We can't do it in componentWillMount() etc... because it's javascript, working in client-side! No any connection to DB. How else?

I need rendered html with data from DB. Server should return HTML with data. Actions working on promises, that's why they don't return data before rendering.

React fetching data with ajax-requests. But do we need send multiple ajax-requests to render one page?...

Well, it's very confusing.

Daryn K.
  • 671
  • 2
  • 12
  • 23
  • 1
    Please, don't minus, explain – Daryn K. Jul 02 '17 at 00:00
  • Yes, you use Ajax requests (XHR), but people tend to use Fetch API or Axios because these have promises. The initial data that you fetch to populate the component has to be initialized in ComponentDidMount(). The others, for exampe if you click something and you want to fetch some data, this should be done as a separate method in the lifecycle. If you specify the stack you are using (e.g. what database do you use?) I can give you a code example – carkod Jan 09 '18 at 22:00
  • Also, you don't send multiple Ajax requests to render a page. You (1) Render the page (2) Fetch the data – carkod Jan 09 '18 at 22:02

1 Answers1

0

You could render the data from server in hidden html component and whenever the website loads on server side. Display those in the view.like

<div id="load-first" style="display:none">{{your_data}}</div>

Now when the page loads then render the inner html's json data or something else in the view like

import React, {Component} from 'react';

class MyComponent extends Component{
    constructor(props){
       super(props);
       this.state={myData: {}}
    }

    componentDidMount(){
       let data = document.getElementById("load-first").innerHTML;
       // if json
       data = JSON.parse(data);
       this.setState({myData: data});
    }

    render(){
       return (
           <div>{this.state.myData}</div>
       );
    }
}
Dipesh Dulal
  • 518
  • 4
  • 8
  • You don't understand. I need server returns rendered from DB data in body of HTTP response. Understand? Such stupid thing as componentDidMount or componentWillMount doesn't work! Because it's JS. JS on client side can't return data from DB in body of HTTP response. – Daryn K. Jul 02 '17 at 00:33
  • In PHP there is function called header() in which you can pass key value pairs. Did you try using that it adds content to the HTTP response header. also, there is a stackoverflow question i came across [link](https://stackoverflow.com/questions/563035/can-i-pass-custom-data-in-the-http-header) have you checked it out. – Dipesh Dulal Jul 02 '17 at 13:07
  • You don't understand again. I don't need any header etc.. I need fetch news in html from server. Without any action dispatches in client. – Daryn K. Jul 02 '17 at 16:14