Last active
December 17, 2016 21:09
-
-
Save BTMPL/d890f0c38e45c6a984f5b3604e4d0faf to your computer and use it in GitHub Desktop.
ImmutableJS for dummies
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
function reduce(state = Immutable.fromJS({ | |
items: { | |
values: [] | |
} | |
}), action = null) { | |
if(action) { | |
switch(action.type) { | |
case "ADD": | |
return state.updateIn(['items','values'], (data) => data.push(action.payload)); | |
case "REMOVE": | |
return state.updateIn(['items','values'], (data) => data.delete(data.findKey((item) => item.id === action.payload.id))) | |
case "UPDATE": | |
return state.updateIn(['items','values'], (data) => data.update(data.findKey((item) => item.id === action.payload.id), (item) => Object.assign({}, item, action.payload))) | |
} | |
} | |
return state; | |
} | |
let state; | |
state = reduce(state, { type: "ADD", payload: { id: 1, value: Math.random() }}); | |
state = reduce(state, { type: "ADD", payload: { id: 2, value: Math.random() }}); | |
state = reduce(state, { type: "ADD", payload: { id: 3, value: Math.random() }}); | |
state = reduce(state, { type: "UPDATE", payload: { id: 2, value: -1 }}); | |
state = reduce(state, { type: "REMOVE", payload: { id: 3 }}); | |
state.getIn(['items','values']).map(i => console.log(i.value)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment