Skip to content

Instantly share code, notes, and snippets.

@turbobabr
Created July 30, 2015 06:35
Show Gist options
  • Save turbobabr/9ace2c69673e65f3efcb to your computer and use it in GitHub Desktop.
Save turbobabr/9ace2c69673e65f3efcb to your computer and use it in GitHub Desktop.
import { createStore } from 'redux';
import _ from 'underscore';
const ADD_ITEM = 'ADD_ITEM';
const REMOVE_ITEM = 'REMOVE_ITEM';
const UPDATE_ITEM = 'UPDATE_ITEM';
const initialState = {
items: [
{
id: 'item01',
name: "Jack"
},
{
id: 'item02',
name: "Howard"
}
]
};
// Reducer
function itemsReducer(state = initialState, action = {}) {
switch(action.type) {
case ADD_ITEM:
return _.extend(state,{
items: state.items.concat([action.item])
});
case REMOVE_ITEM:
return _.extend(state,{
items: _.filter(state.items,(item) => item.id !== action.id)
});
case UPDATE_ITEM:
return _.extend(state,{
items: _.map(state.items,(item) => {
return item.id === action.id ? { ...item, name: action.name } : item;
})
});
default:
return state;
}
}
let store = createStore(itemsReducer);
store.subscribe(() => {
console.log(`Current state is:
------------------------------`);
_.each(store.getState().items,(item) => {
console.log(`${item.id}: ${item.name}`);
});
console.log(`List contains ${store.getState().items.length} items
`);
});
store.dispatch({
type: ADD_ITEM,
item: {
id: 'item03',
name: "Ivan"
}
});
store.dispatch({
type: REMOVE_ITEM,
id: 'item02'
});
store.dispatch({
type: UPDATE_ITEM,
id: 'item03',
name: "Ivan IV (updated)"
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment