Skip to content

Instantly share code, notes, and snippets.

@kettanaito
Last active May 22, 2018 07:40
Show Gist options
  • Save kettanaito/5e1576a0c62f1a3e5da976a3dd0c4baf to your computer and use it in GitHub Desktop.
Save kettanaito/5e1576a0c62f1a3e5da976a3dd0c4baf to your computer and use it in GitHub Desktop.
Redux - Selector
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