Created
June 12, 2016 16:10
-
-
Save danieldunderfelt/b7db7709154d7b95b111ab583622f51a to your computer and use it in GitHub Desktop.
Serializing and hydrating state with MobX
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* App creator */ | |
import { extendObservable } from 'mobx' | |
import AppStore from '../app/AppStore' | |
export default (initialState = false) => { | |
const stores = { | |
App: AppStore | |
} | |
if(initialState) { | |
Object.keys(stores).forEach(store => { | |
if(typeof initialState[store] !== 'undefined') { | |
extendObservable(stores[store], initialState[store]) | |
} | |
}) | |
} | |
return stores | |
} | |
/* Client entry point */ | |
... | |
// Store is the app creator function above | |
const initialState = store(window.__INITIAL_STATE__) | |
render( | |
<Root store={ initialState } /> | |
document.getElementById('root') | |
) | |
/* Server renderer */ | |
... | |
function renderTemplate(component = false, data = {}) { | |
res.send('<!doctype html>\n' + ReactDOM.renderToStaticMarkup(<Html component={ component } data={ data } />)) | |
} | |
// Create all stores | |
const state = store() | |
// Mount app | |
const component = ( | |
<Root store={ state }> | |
<RouterContext {...renderProps} /> | |
</Root> | |
) | |
// state contains data now | |
renderTemplate(component, toJS(state)) | |
... | |
/* Server template */ | |
... | |
// Serialize the data into a global var, see "client entry" above how to merge it into the state | |
<script dangerouslySetInnerHTML={{ __html: `window.__INITIAL_STATE__ = ${serialize(data)}` }}></script> | |
... |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment