Created
March 22, 2017 07:14
-
-
Save RealDeanZhao/d1f24474a182683dab34ee1d623d65fe to your computer and use it in GitHub Desktop.
redux-orm customized actionHandler integrated with react-act
This file contains 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
// In the model class | |
static actionHandler() { | |
return { | |
[documentAction.receiveDocumentList]: (state, payload) => { | |
const session = orm.session(state || state.getEmptyState()); | |
const { DocumentModel } = session; | |
DocumentModel.all().toModelArray().forEach(model => { | |
model.update({ showInList: false, selected: false }); | |
}); | |
payload.forEach(document => { | |
if (DocumentModel.hasId(document.id)) { | |
DocumentModel.withId(document.id).update({ ...document, showInList: true, selected: false }); | |
} else { | |
DocumentModel.create({ | |
...document, | |
allLinesSelected: true, | |
showInList: true, | |
selected: false | |
}); | |
} | |
}); | |
return session.state; | |
}, | |
[documentAction.selectDocument]: (state, payload) => { | |
const session = orm.session(state || state.getEmptyState()); | |
const { DocumentModel } = session; | |
if (DocumentModel.hasId(payload)) { | |
const documentInstance = DocumentModel.withId(payload); | |
documentInstance.update({ selected: !documentInstance.selected }); | |
} | |
return session.state; | |
} | |
} | |
} | |
// The reducers for the orm | |
import { createReducer } from 'redux-act'; | |
import orm from '../orm'; | |
export default function createOrmReducer() { | |
const session = orm.session(orm.getEmptyState()); | |
let actionHandler = {}; | |
session.sessionBoundModels.forEach(modelClass => { | |
if (typeof modelClass.actionHandler === 'function') { | |
Object.assign(actionHandler, modelClass.actionHandler()); | |
} | |
}); | |
return createReducer(actionHandler, session.state); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment