Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass data from express server to react views?

I have a simple express server with a connection to a orientdb database. I need to pass information from express to react views. For example, in express I have:

router.get('/', function(req, res, next) {
  Vertex.getFromClass('Post').then(
    function (posts) {
      res.render('index', { title: 'express' });
    }
  );
});

So, in this example, I need to have in my react index component, the posts variable to set the state of the componenent. (I'm using react only in the frontend, not server-side)

class IndexPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    };
  }

  render() {
    return (
      <div>
        <Posts posts={posts} />
      </div>
    );
  }
}

How can I get the posts in react from express?

I found that maybe I can do an ajax request from react, but I think that that isn't the best way.

If I need to get that posts in a real time way, using socket.io for example, what are the differences?

PD: In express I have the possibility to use some template engine like handlebars or hogan. Can this template engines help in this topic?

Thanks!!!

like image 628
Santiago Aranguri Avatar asked Oct 16 '16 14:10

Santiago Aranguri


Video Answer


1 Answers

I think your best option is to indeed make some kind of network request from the client. If you aim to keep the app simple and do not want a State Management library (e.g. Redux), you could do something like

class IndexPage extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      posts: []
    };
  }

  componentDidMount() {
    fetch('/') // or whatever URL you want
      .then((response) => response.json())
      .then((posts) => this.setState({
        posts: posts,
      });
  }

  render() {
    return (
      <div>
        <Posts posts={this.state.posts} />
      </div>
    );
  }
}

In your response there should be a JSON representation of the posts collection.

Also note the render method and accessing the posts.

For more on Fetch API see MDN (please also note that you will need a polyfill for older browsers for it).

EDIT: For socket.io I'd store the instance of it somewhere and pass it as a prop to the component. Then you can do something like

class IndexPage extends React.Component {
  ...
  componentDidMount() {
    this.props.socket.on('postReceived', this.handleNewPost);
  }
  handleNewPost = (post) => {
    this.setState({
      posts: [
        ...this.state.posts,
        post,
      ],
    });
  }
  ...
}

The server-side part is similar, see for example Socket.io Chat example.

like image 117
Dan Homola Avatar answered Oct 05 '22 10:10

Dan Homola