Skip to content

Instantly share code, notes, and snippets.

@mrgenixus
Created December 2, 2016 22:53
Show Gist options
  • Select an option

  • Save mrgenixus/049eab4e86c91040c9164483881793ff to your computer and use it in GitHub Desktop.

Select an option

Save mrgenixus/049eab4e86c91040c9164483881793ff to your computer and use it in GitHub Desktop.
plan to eat redux
// redux starts with the store.- ish
const store = Redux.createStore(function(state, action) {
return rootReducer(state, action);
});
// next, components and other kinds of (what I'll call) mappers dispatch actions to the store
store.dispatch({
type: 'THIS_IS_A_TYPE_OF_ACTION'
});
//then, the root reducer is called with the state of the store, and the action
function rootReducer(state={}, action) {
switch(action.type) {
case 'THIS_IS_A_TYPE_OF_ACTION':
return { ...state, type: 'action' };
default
return state;
}
};
// then, once the reducer (and any other delegate reducers) have finished
// then any subscibers to the store, are called.
// wait what?
const unsubscribe = store.subscribe(function() {
ReactDOM.render(<App store={ store.getState() } />, document.getElementById('app');
});
const MySpecialSnowflakeComponent = React.createClass({
componentDidMount: function() {
this.unsubscribe = store.subscribe(this._onChange.bind(this));
},
conponentWillUnmount: function() {
this.unsubscribe();
},
_onChange: function() {
const { flakes } = store.getState();
this.setState({ flakes });
},
render: function() {
return (
<ul>
{ _.map(this.state.flakes, flake => {
<li>{ flake.title }</li>
}) }
</ul>
);
}
});
// in Plan to eat, we use a special object property 'persisted' to indicate that an item has been modified on the client
store.dispath({
type: 'EDIT_SNOWFLAKE',
title: 'my other special snowflake',
id: '5e4c6dad-7a80-4dec-93e1-6e40583cad1e'
});
// =>
const storeState = {
flakes: [
{ title: 'my other special snowflake', id: '5e4c6dad-7a80-4dec-93e1-6e40583cad1e', persisted: false }
]
}
// Then a store subscriber (called the synchronization manager) delegates updating the server state from the client
function flakeSynchronizer(state, dispatch, next) {
function updateSuccess(flake) {
dispatch({
type: 'EDIT_SNOWFLAKE', id: unpersistedFlake.id, persisted: true
});
}
function updateFailure(error) {
dispatch({
type: 'PERISTENCE_ERRPR', error
});
}
const unpersistedFlake = _.find(state.flakes, { persisted: false });
if (unpersistedFlake) {
FlakeRepository
.update(unpersistedFlake.externalId, _.pick(unpersistedFlake, 'title'))
.then(updateSuccess, updateFailure);
} else {
next();
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment