Permalink
Browse files

fetches data before rendering component on server

  • Loading branch information...
rogerjin12 committed May 24, 2017
1 parent 525c625 commit 5fdd453e31ab08dfdc8b44261696d4ed89fbb719
Showing with 23 additions and 21 deletions.
  1. +13 −14 hello.js
  2. +2 −1 package.json
  3. +8 −6 server.js
View
@@ -1,25 +1,15 @@
import React from 'react';
import Butter from 'buttercms'
import Transmit from 'react-transmit';
const butter = Butter('b60a008584313ed21803780bc9208557b3b49fbb');
var Hello = React.createClass({
getInitialState: function() {
return {loaded: false};
},
componentWillMount: function() {
butter.post.list().then((resp) => {
this.setState({
loaded: true,
resp: resp.data
})
});
},
render: function() {
if (this.state.loaded) {
if (this.props.posts) {
return (
<div>
{this.state.resp.data.map((post) => {
{this.props.posts.data.map((post) => {
return (
<div key={post.slug}>{post.title}</div>
)
@@ -32,4 +22,13 @@ var Hello = React.createClass({
}
});
export default Hello;
export default Transmit.createContainer(Hello, {
// These must be set or else it would fail to render
initialVariables: {},
// Each fragment will be resolved into a prop
fragments: {
posts() {
return butter.post.list().then((resp) => resp.data);
}
}
});
View
@@ -11,7 +11,8 @@
"express": "^4.15.3",
"path": "^0.12.7",
"react": "^0.14.8",
"react-dom": "^0.14.8"
"react-dom": "^0.14.8",
"react-transmit": "^3.2.0"
},
"devDependencies": {
"webpack": "^1.12.14",
View
@@ -4,16 +4,18 @@ import path from 'path';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import Hello from './Hello.js';
import Transmit from 'react-transmit';
function handleRender(req, res) {
const html = ReactDOMServer.renderToString(<Hello />);
Transmit.renderToString(Hello).then(({reactString, reactData}) => {
fs.readFile('./index.html', 'utf8', function (err, data) {
if (err) throw err;
fs.readFile('./index.html', 'utf8', function (err, data) {
if (err) throw err;
const document = data.replace(/<div id="app"><\/div>/, `<div id="app">${reactString}</div>`);
const output = Transmit.injectIntoMarkup(document, reactData, ['/build/client.js']);
const document = data.replace(/<div id="app"><\/div>/, `<div id="app">${html}</div>`);
res.send(document);
res.send(document);
});
});
}

0 comments on commit 5fdd453

Please sign in to comment.