Skip to content

Instantly share code, notes, and snippets.

@pocheptsov
Created February 7, 2019 22:29
Show Gist options
  • Save pocheptsov/afb5d403beaf622cc4b39166cd813b34 to your computer and use it in GitHub Desktop.
Save pocheptsov/afb5d403beaf622cc4b39166cd813b34 to your computer and use it in GitHub Desktop.
Initial redux-orm state loading
import orm from 'schema/orm'
export function loadStateReducer(state = orm.getEmptyState(), payload) {
// Create a Redux-ORM session from our entities "tables"
const session = orm.session(state)
const parseEntity = (modelName, stateSlotName) => {
const ModelClass = session[modelName]
const modelStates = payload.entities[stateSlotName]
if (modelStates) {
// generic entities load
// parse by default will upsert model instance
return modelStates.map ?
modelStates.map(modelState => ModelClass.parse(modelState)) :
ModelClass.parse(modelStates)
}
}
// pay attention to our custom `stateSlotName` model class property
orm.getModelClasses().forEach(modelClass => {
const ModelClass = session[modelClass.modelName]
parseEntity(modelClass.modelName, ModelClass.stateSlotName)
})
return session.state
}
import { renderToString } from 'react-dom/server'
import configureStore from 'common/store'
import { loadStateReducer } from 'product/reducers'
export const getInitialState = () => {
const initialState = {
// !!!!!YOUR INITIAL JSON STATE HERE!!!!
}
return {
orm: loadStateReducer(undefined, initialState)
}
}
...
const store = configureStore({ initialState: getInitialState(), reducers, rootSaga })
const html = renderToString(
<Provider store={store}>
<App />
</Provider>
)
...
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment