Last active
December 20, 2017 17:02
-
-
Save ydatech/05d5356fd2298915d1374e2d79be1861 to your computer and use it in GitHub Desktop.
Todo React Redux for https://learnreact.blogspot.com
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * 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; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * 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