Last active
May 22, 2018 07:40
-
-
Save kettanaito/5e1576a0c62f1a3e5da976a3dd0c4baf 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' | |
const getTotalPrice = items => items.reduce((acc, item) => { | |
return acc + item.get('price') | |
}, 0) | |
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)) | |
return state | |
.set('items', nextItems) | |
.set('totalPrice', getTotalPrice(nextItems)) | |
} | |
case REMOVE_ITEM: { | |
const { itemId } = action | |
const nextItems = state.get('items').filter(item => item.get('id') !== itemId) | |
return state | |
.set('items', nextItems) | |
.set('totalPrice', getTotalPrice(nextItems)) | |
} | |
default: | |
return state | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment