Skip to content

Instantly share code, notes, and snippets.

@hiasinho
Last active June 3, 2016 06:06
Show Gist options
  • Save hiasinho/d73eff8e27625d4abe733c39e02fde2b to your computer and use it in GitHub Desktop.
Save hiasinho/d73eff8e27625d4abe733c39e02fde2b to your computer and use it in GitHub Desktop.
Reducer Adapters
import Immutable from 'immutable';
export const reduce = {
addTodo: (state, todo) => {
return state.push(Immutable.fromJS({
id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
completed: false,
text: action.text
}))
},
deleteTodo: (state, id) => {
return state.filter(todo => todo.get('id') !== id)
}
}
export const query = {
todos: (state) => {
return state.toJS()
}
}
import objectAssign from 'object-assign';
export const reduce = {
addTodo: (state, todo) => {
return state.slice(0).concat([{
id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1,
completed: false,
text: action.text
}])
},
deleteTodo: (state, id) => {
return state.slice(0).filter(todo =>
todo.id !== action.id
)
}
}
export const query = {
todos: (state) => {
return state
}
}
import Immutable from 'immutable';
export const initialState = [];
export const $$initialState = Immutable.fromJS(initialState);
import React, {PropTypes} from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import TodoActions as actions from '../actions';
import TodoList from '../components/TodoList';
// This is for POJO
import { query } from '../utils/helpersPojo'
// Uncomment this is for Immutable.js
// import { query } from '../utils/helpersImmutable'
export const Todos = (props) => {
return (
<TodoList
actions={this.props.actions}
todos={this.props.todos}
/>
);
};
Todos.propTypes = {
actions: PropTypes.object.isRequired,
todos: PropTypes.array.isRequired
};
function mapStateToProps(state) {
return {
todos: query.todos(state)
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(TodoActions, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Todos);
import { ADD_TODO, DELETE_TODO } from '../constants/ActionTypes'
// This is for POJO
import initialState from 'initialState'
import { reduce } from '../utils/helpersPojo'
// Uncomment this is for Immutable.js
// import $$initialState as initialState from 'initialState'
// import { reduce } from '../utils/helpersImmutable'
export default function todos(state = initialState, action) {
const { todo, id } = action
switch (action.type) {
case ADD_TODO:
return reduce.addTodo(state, todo)
case DELETE_TODO:
return reduce.deleteTodo(state, id)
default:
return state
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment