Last active
May 22, 2018 07:34
-
-
Save kettanaito/4e49ffbc1d34982a608daeb0a879b687 to your computer and use it in GitHub Desktop.
Redux - Selector
This file contains hidden or 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
import initialState from './initial-state' | |
import { ADD_ITEM, REMOVE_ITEM } from './action-types' | |
export default function cart(state = initialState, action) { | |
switch (action.type) { | |
case ADD_ITEM: { | |
const { item } = action | |
const nextItems = state.update('items', items => items.push(item)) | |
const nextTotalPrice = nextItems.reduce((acc, item) => { | |
return acc + item.get('price') | |
}, 0) | |
return state | |
.set('items', nextItems) | |
.set('totalPrice', nextTotalPrice) | |
} | |
case REMOVE_ITEM: { | |
const { itemId } = action | |
const nextItems = state.get('items').filter(item => item.get('id') !== itemId) | |
const nextTotalPrice = nextItems.reduce((acc, item) => { | |
return acc + item.get('price') | |
}, 0) | |
return state | |
.set('items', nextItems) | |
.set('totalPrice', nextTotalPrice) | |
} | |
default: | |
return state | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment