adding some redux steps

This commit is contained in:
Ken Chau
2019-02-16 17:00:47 -08:00
parent e143a0e820
commit 7fc326b0cb
22 changed files with 2096 additions and 2173 deletions

View File

@@ -0,0 +1,3 @@
export const addTodo = (label: string) => ({ type: 'addTodo', label });
export const remove = (id: string) => ({ type: 'remove', id });
export const complete = (id: string) => ({ type: 'complete', id });

15
step2-06/src/index.tsx Normal file
View File

@@ -0,0 +1,15 @@
import { reducer } from './reducers';
import { createStore, compose } from 'redux';
import { addTodo } from './actions';
declare var window: any;
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, {}, composeEnhancers());
console.log(store.getState());
store.dispatch(addTodo('hello'));
store.dispatch(addTodo('world'));
console.log(store.getState());

View File

@@ -0,0 +1,19 @@
import { Store } from '../store';
import { addTodo, remove, complete } from './pureFunctions';
let index = 0;
export function reducer(state: Store, payload: any): Store {
switch (payload.type) {
case 'addTodo':
return addTodo(state, payload.label);
case 'remove':
return remove(state, payload.id);
case 'complete':
return complete(state, payload.id);
}
return state;
}

View File

@@ -0,0 +1,20 @@
import { addTodo } from './pureFunctions';
import { Store } from '../store';
describe('TodoApp reducers', () => {
it('can add an item', () => {
const state = <Store>{
todos: {},
filter: 'all'
};
const newState = addTodo(state, 'item1');
const keys = Object.keys(newState.todos);
expect(newState).not.toBe(state);
expect(keys.length).toBe(1);
expect(newState.todos[keys[0]].label).toBe('item1');
expect(newState.todos[keys[0]].completed).toBeFalsy();
});
});

View File

@@ -0,0 +1,34 @@
import { Store } from '../store';
let index = 0;
export function addTodo(state: Store, label: string): Store {
const { todos } = state;
const id = index++;
return {
...state,
todos: { ...todos, [id]: { label, completed: false } }
};
}
export function remove(state: Store, id: string) {
const newTodos = { ...state.todos };
delete newTodos[id];
return {
...state,
todos: newTodos
};
}
export function complete(state: Store, id: string) {
const newTodos = { ...this.state.todos };
newTodos[id].completed = !newTodos[id].completed;
return {
...state,
todos: newTodos
};
}

View File

@@ -0,0 +1,14 @@
export type FilterTypes = 'all' | 'active' | 'completed';
export interface TodoItem {
label: string;
completed: boolean;
}
export interface Store {
todos: {
[id: string]: TodoItem;
};
filter: FilterTypes;
}