Permalink
Browse files

Part 2: Enabling SSR

  • Loading branch information...
vfeskov committed Dec 21, 2017
1 parent 2e2619a commit 565abd80d7c1bb5e111dc4b4c18ebfd115dd574c
@@ -15,7 +15,7 @@
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build && npm run move-build-to-server",
"move-build-to-server": "mv build _build && mv _build ../server && cd ../server && rm -rf public && mv _build public",
"move-build-to-server": "mv build _build && mv _build ../server && cd ../server && rm -rf public && mv _build public && mv public/index.html public/layout.html",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
@@ -18,12 +18,16 @@ export class AppComponent extends Component {
}

componentDidMount () {
this.props.fetchPosts()
const { inited, fetchPosts } = this.props
if (!inited) { fetchPosts() }
}
}

export const App = connect(
state => ({ posts: state.posts }),
state => ({
posts: state.posts,
inited: state.inited
}),
dispatch => bindActionCreators(actionCreators, dispatch)
)(AppComponent)

@@ -3,13 +3,15 @@ import 'isomorphic-fetch'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import registerServiceWorker from './registerServiceWorker'
import { unregister } from './registerServiceWorker'
import thunkMiddleware from 'redux-thunk'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import { root } from './reducers'

const store = createStore(root, applyMiddleware(thunkMiddleware))
const initState = window.__INIT_STATE__ && JSON.parse(window.__INIT_STATE__)

const store = createStore(root, initState, applyMiddleware(thunkMiddleware))

ReactDOM.render(
<Provider store={store}>
@@ -18,4 +20,4 @@ ReactDOM.render(
document.getElementById('root')
)

registerServiceWorker()
unregister()
@@ -1,6 +1,8 @@
import { combineReducers } from 'redux'
import { posts } from './posts'
import { inited } from './inited'

export const root = combineReducers({
posts
posts,
inited
})
@@ -0,0 +1,11 @@
import { RECEIVE_POSTS, ERROR_POSTS } from '../actions'

export function inited (state = false, action) {
switch (action.type) {
case RECEIVE_POSTS:
case ERROR_POSTS:
return true
default:
return state
}
}
@@ -0,0 +1,23 @@
import React from 'react'
import { createStore } from 'redux'
import { root } from './reducers'
import { receivePosts, errorPosts } from './actions'
import { Provider } from 'react-redux'
import { renderToString } from 'react-dom/server'
import { App } from './App'

export function renderToStrings (posts) {
const store = createStore(root)
store.dispatch(
posts ? receivePosts(posts) : errorPosts()
)

const html = renderToString(
<Provider store={store}>
<App />
</Provider>
)
const state = JSON.stringify(JSON.stringify(store.getState()))

return { html, state }
}
Oops, something went wrong.

0 comments on commit 565abd8

Please sign in to comment.