Skip to content

Instantly share code, notes, and snippets.

@ydatech
Last active December 20, 2017 17:02
Show Gist options
  • Select an option

  • Save ydatech/05d5356fd2298915d1374e2d79be1861 to your computer and use it in GitHub Desktop.

Select an option

Save ydatech/05d5356fd2298915d1374e2d79be1861 to your computer and use it in GitHub Desktop.
Todo React Redux for https://learnreact.blogspot.com
/*
* path: src/reducers/index.js
* description: this file is a rootReducer that combine all reducers including todo reducer
*/
import { combineReducers } from 'redux';
//reducers
import todo from './todo';
const rootReducer = combineReducers({
todo
});
export default rootReducer;
/*
* path: src/reducers/todo.js
* description: this file contains todo reducer, action types and creators
*/
// action types
export const types = {
CREATE: 'app/todo/CREATE',
UPDATE: 'app/todo/UPDATE',
DELETE: 'app/todo/DELETE'
}
// initial state
export const initialState = {
items: []
}
// reducer
export default (state = initialState, action) => {
switch (action.type) {
case types.CREATE:
return {
...state,
items: [
action.payload.item,
...state.items
]
};
case types.UPDATE:
return {
...state,
items: state.items.map(item => {
if (item.id === action.payload.item.id) {
return {
...item,
...action.payload.item
}
}
return item;
})
};
case types.DELETE:
const deleteIndex = state.items.findIndex((item) => (item.id === action.payload.item.id));
if (deleteIndex > -1) {
const deletedItems = [
...state.items.slice(0, deleteIndex),
...state.items.slice(deleteIndex + 1)
];
return {
...state,
items: deletedItems
};
}
return state;
default:
return state;
}
};
// action creators
export const actions = {
create: (item) => ({ type: types.CREATE, payload: { item } }),
update: (item) => ({ type: types.UPDATE, payload: { item } }),
delete: (item) => ({ type: types.DELETE, payload: { item } })
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment