Skip to content

Instantly share code, notes, and snippets.

@reggi
Last active February 10, 2017 13:11
Show Gist options
  • Select an option

  • Save reggi/adbf080ec945d8afc6a8c10de3f70997 to your computer and use it in GitHub Desktop.

Select an option

Save reggi/adbf080ec945d8afc6a8c10de3f70997 to your computer and use it in GitHub Desktop.
import 'rxjs'
import { createStore, applyMiddleware } from 'redux'
import { combineEpics, createEpicMiddleware } from 'redux-observable'
import { filter } from 'lodash'
import {APP_NAME} from './app'
const REDUCER = 'puppy'
const SELECT = `${APP_NAME}/${REDUCER}/SELECT`
const DESELECT = `${APP_NAME}/${REDUCER}/DESELECT`
const HIDE = `${APP_NAME}/${REDUCER}/HIDE`
const PUSH = `${APP_NAME}/${REDUCER}/PUSH`
const SELECTED = `${APP_NAME}/${REDUCER}/SELECTED`
const DESELECTED = `${APP_NAME}/${REDUCER}/DESELECTED`
const HIDDEN = `${APP_NAME}/${REDUCER}/HIDDEN`
const PUSHED = `${APP_NAME}/${REDUCER}/PUSHED`
const defaultState = {
selectedPuppyIds: []
}
export default function reducer (state = defaultState, action) {
switch (action.type) {
// case SELECT:
// return {
// ...state,
// selectedPuppyIds: [...state.selectedPuppyIds, action.puppyId]
// }
// case DESELECT:
// let selectedPuppyIds = filter(state.selectedPuppyIds, id => id !== action.puppyId)
// return {
// ...state,
// selectedPuppyIds
// }
case SELECTED:
return {
...state,
selectedPuppyIds: action.selectedPuppyIds
}
case DESELECTED:
return {
...state,
selectedPuppyIds: action.selectedPuppyIds
}
case HIDDEN:
return state
case PUSHED:
return state
default:
return state
}
}
export const selectPuppyAction = (puppyId) => ({ type: SELECT, puppyId })
export const deselectPuppyAction = (puppyId) => ({ type: DESELECT, puppyId })
export const hidePuppyAction = (puppyId) => ({ type: HIDE, puppyId })
export const pushPuppyAction = (puppyId) => ({ type: PUSH, puppyId })
export const deselectPuppyEpic = (action$, store) => {
return action$.ofType(DESELECT)
.map(action => {
let state = store.getState()
let selectedPuppyIds = filter(state.selectedPuppyIds, id => id !== action.puppyId)
return {
type: DESELECTED,
selectedPuppyIds
}
})
}
export const selectPuppyEpic = (action$, store) => {
return action$.ofType(SELECT)
.map(action => {
let state = store.getState()
return {
type: SELECTED,
selectedPuppyIds: [...state.selectedPuppyIds, action.puppyId]
}
})
}
export const rootEpic = combineEpics(
deselectPuppyEpic,
selectPuppyEpic
)
export const epicMiddleware = createEpicMiddleware(rootEpic)
const store = createStore(
reducer,
applyMiddleware(epicMiddleware)
)
store.dispatch(selectPuppyAction(1))
store.dispatch(selectPuppyAction(2))
store.dispatch(deselectPuppyAction(1))
store.dispatch(selectPuppyAction(3))
store.subscribe(() => {
console.log(store.getState())
})
console.log(store.getState())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment