Skip to content

Instantly share code, notes, and snippets.

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