integrating immer

This commit is contained in:
Ken
2019-01-30 14:33:48 -08:00
parent a61d89ea14
commit c44af2a38f
7 changed files with 82 additions and 31 deletions

View File

@@ -1,13 +1,14 @@
import { Reducer } from 'redux';
import { ActionTypes, TodoAction } from '../actions';
import { Draft, produce } from 'immer';
export function createReducer<T>(
initialState: T,
handlers: { [actionType in ActionTypes]?: (state: T, action: TodoAction) => T }
handlers: { [actionType in ActionTypes]?: (state: Draft<T>, action: TodoAction) => T }
): Reducer<T> {
return function reducer(state = initialState, action: TodoAction): T {
if (handlers.hasOwnProperty(action.type)) {
return handlers[action.type](state, action);
return produce(state, draft => handlers[action.type](draft, action));
} else {
return state;
}

View File

@@ -5,17 +5,23 @@ import { combineReducers } from 'redux';
let counter = 0;
export const reducer = combineReducers<Store>({
todos: createReducer(
todos: createReducer<Store['todos']>(
{},
{
add(state, action) {
add(draft, action) {
const id = String(counter++);
return { ...state, [id]: { label: action.label, completed: false } };
draft[id] = { label: action.label, completed: false };
return draft;
},
remove(draft, action) {
delete draft[action.id];
return draft;
}
}
),
filter: createReducer<FilterTypes>('all', {
filter(state, action) {
filter(draft, action) {
return action.filter;
}
})