mirror of
https://github.com/microsoft/frontend-bootcamp.git
synced 2026-01-26 14:56:42 +08:00
Added exercises
This commit is contained in:
@@ -1,25 +1,17 @@
|
||||
# Step 2.6 - Redux: Dispatching actions and examining state (Exercise)
|
||||
# Step 2.6: Redux: React Binding (Exercise)
|
||||
|
||||
[Lessons](../) | [Exercise](./exercise/) | [Demo](./demo/)
|
||||
|
||||
## Visualize state changes with Chrome extension
|
||||
## Bind Redux Store with Class Component
|
||||
|
||||
If you still have `npm test` running from the previous step, stop it with `ctrl+C`. Start the app by running `npm start` from the root of the `frontend-bootcamp` folder. Click the "exercise" link under day 2 step 6.
|
||||
1. Open `exercise/src/components/TodoHeader.tsx`.
|
||||
|
||||
1. Install the [Redux DevTools extension](https://github.com/zalmoxisus/redux-devtools-extension)
|
||||
- [Chrome](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd)
|
||||
- [Firefox](https://addons.mozilla.org/en-US/firefox/addon/reduxdevtools/)
|
||||
2. Just like the 2.4 exercise, implement `onAdd` and `onFilter` using `this.context.dispatch()` calls to dispatch actions.
|
||||
|
||||
2. Hit F12 (`cmd+option+I` on Mac) and open the inspector panel entitled **Redux**
|
||||
## Bind Redux Store with Functional Component
|
||||
|
||||
3. Modify `exercise/src/index.tsx` to dispatch actions (you're not limited to adding todos; you can also remove and clear)
|
||||
1. Open `exercise/src/components/TodoFooter.tsx`.
|
||||
|
||||
4. Explore the actions' effects using the extension
|
||||
2. Follow the instructions in the file to replace the `todos` const using the `useMappedState()` hook.
|
||||
|
||||
## Playing with dispatching actions inside tests
|
||||
|
||||
Stop the app using `ctrl+C` and start the tests by running `npm test`.
|
||||
|
||||
1. Open `exercise/src/reducers/reducer.spec.ts`
|
||||
|
||||
2. Follow the instructions to fill out the reducer tests
|
||||
3. Retrieve the dispatch function with `useDispatch()` hook.
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import uuid from 'uuid/v4';
|
||||
|
||||
export const actions = {
|
||||
addTodo: (label: string) => ({ type: 'addTodo', id: uuid(), label })
|
||||
addTodo: (label: string) => ({ type: 'addTodo', id: uuid(), label }),
|
||||
remove: (id: string) => ({ type: 'remove', id }),
|
||||
complete: (id: string) => ({ type: 'complete', id }),
|
||||
clear: () => ({ type: 'clear' }),
|
||||
setFilter: (filter: string) => ({ type: 'setFilter', filter }),
|
||||
edit: (id: string, label: string) => ({ type: 'edit', id, label })
|
||||
};
|
||||
|
||||
17
step2-06/exercise/src/components/TodoApp.tsx
Normal file
17
step2-06/exercise/src/components/TodoApp.tsx
Normal file
@@ -0,0 +1,17 @@
|
||||
import React from 'react';
|
||||
import { Stack } from 'office-ui-fabric-react';
|
||||
import { TodoFooter } from './TodoFooter';
|
||||
import { TodoHeader } from './TodoHeader';
|
||||
import { TodoList } from './TodoList';
|
||||
|
||||
export const TodoApp = () => {
|
||||
return (
|
||||
<Stack horizontalAlign="center">
|
||||
<Stack style={{ width: 400 }} gap={25}>
|
||||
<TodoHeader />
|
||||
<TodoList />
|
||||
<TodoFooter />
|
||||
</Stack>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
24
step2-06/exercise/src/components/TodoFooter.tsx
Normal file
24
step2-06/exercise/src/components/TodoFooter.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import React from 'react';
|
||||
import { DefaultButton, Stack, Text } from 'office-ui-fabric-react';
|
||||
import { actions } from '../actions';
|
||||
import { useMappedState, useDispatch } from 'redux-react-hook';
|
||||
|
||||
export const TodoFooter = () => {
|
||||
// TODO: make use of useMappedState(state => state) and the useDispatch functions to get
|
||||
// the Redux store and dispatching actions
|
||||
// HINT: const { todos } = useMappedState(...);
|
||||
// HINT: useDispatch() here too.
|
||||
const todos = {};
|
||||
const dispatch = (...args: any[]) => {};
|
||||
|
||||
const itemCount = Object.keys(todos).filter(id => !todos[id].completed).length;
|
||||
|
||||
return (
|
||||
<Stack horizontal horizontalAlign="space-between">
|
||||
<Text>
|
||||
{itemCount} item{itemCount === 1 ? '' : 's'} left
|
||||
</Text>
|
||||
<DefaultButton onClick={() => dispatch(actions.clear())}>Clear Completed</DefaultButton>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
67
step2-06/exercise/src/components/TodoHeader.tsx
Normal file
67
step2-06/exercise/src/components/TodoHeader.tsx
Normal file
@@ -0,0 +1,67 @@
|
||||
import React from 'react';
|
||||
import { Stack, Text, Pivot, PivotItem, TextField, PrimaryButton } from 'office-ui-fabric-react';
|
||||
import { FilterTypes } from '../store';
|
||||
import { actions } from '../actions';
|
||||
import { StoreContext } from 'redux-react-hook';
|
||||
|
||||
interface TodoHeaderState {
|
||||
labelInput: string;
|
||||
}
|
||||
|
||||
export class TodoHeader extends React.Component<{}, TodoHeaderState> {
|
||||
constructor(props: {}) {
|
||||
super(props);
|
||||
this.state = { labelInput: undefined };
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Stack gap={10}>
|
||||
<Stack horizontal horizontalAlign="center">
|
||||
<Text variant="xxLarge">todos</Text>
|
||||
</Stack>
|
||||
|
||||
<Stack horizontal gap={10}>
|
||||
<Stack.Item grow>
|
||||
<TextField
|
||||
placeholder="What needs to be done?"
|
||||
value={this.state.labelInput}
|
||||
onChange={this.onChange}
|
||||
styles={props => ({
|
||||
...(props.focused && {
|
||||
field: {
|
||||
backgroundColor: '#c7e0f4'
|
||||
}
|
||||
})
|
||||
})}
|
||||
/>
|
||||
</Stack.Item>
|
||||
<PrimaryButton onClick={this.onAdd}>Add</PrimaryButton>
|
||||
</Stack>
|
||||
|
||||
<Pivot onLinkClick={this.onFilter}>
|
||||
<PivotItem headerText="all" />
|
||||
<PivotItem headerText="active" />
|
||||
<PivotItem headerText="completed" />
|
||||
</Pivot>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
private onAdd = () => {
|
||||
// TODO: Fill in a dispatch call to add the todo item
|
||||
// HINT: this.context.dispatch(...);
|
||||
this.setState({ labelInput: undefined });
|
||||
};
|
||||
|
||||
private onChange = (evt: React.FormEvent<HTMLInputElement>, newValue: string) => {
|
||||
this.setState({ labelInput: newValue });
|
||||
};
|
||||
|
||||
private onFilter = (item: PivotItem) => {
|
||||
// TODO: Fill in the dispatch call to set the filter
|
||||
// HINT: this.context.dispatch(...);
|
||||
};
|
||||
}
|
||||
|
||||
// TODO: set the context type of this Class to StoreContext
|
||||
19
step2-06/exercise/src/components/TodoList.tsx
Normal file
19
step2-06/exercise/src/components/TodoList.tsx
Normal file
@@ -0,0 +1,19 @@
|
||||
import React from 'react';
|
||||
import { Stack } from 'office-ui-fabric-react';
|
||||
import { TodoListItem } from './TodoListItem';
|
||||
import { useMappedState } from 'redux-react-hook';
|
||||
|
||||
export const TodoList = () => {
|
||||
const { filter, todos } = useMappedState(state => state);
|
||||
const filteredTodos = Object.keys(todos).filter(id => {
|
||||
return filter === 'all' || (filter === 'completed' && todos[id].completed) || (filter === 'active' && !todos[id].completed);
|
||||
});
|
||||
|
||||
return (
|
||||
<Stack gap={10}>
|
||||
{filteredTodos.map(id => (
|
||||
<TodoListItem key={id} id={id} />
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
78
step2-06/exercise/src/components/TodoListItem.tsx
Normal file
78
step2-06/exercise/src/components/TodoListItem.tsx
Normal file
@@ -0,0 +1,78 @@
|
||||
import React from 'react';
|
||||
import { Stack, Checkbox, IconButton, TextField, DefaultButton } from 'office-ui-fabric-react';
|
||||
import { actions } from '../actions';
|
||||
import { StoreContext } from 'redux-react-hook';
|
||||
|
||||
interface TodoListItemProps {
|
||||
id: string;
|
||||
}
|
||||
|
||||
interface TodoListItemState {
|
||||
editing: boolean;
|
||||
editLabel: string;
|
||||
}
|
||||
|
||||
export class TodoListItem extends React.Component<TodoListItemProps, TodoListItemState> {
|
||||
constructor(props: TodoListItemProps) {
|
||||
super(props);
|
||||
this.state = { editing: false, editLabel: undefined };
|
||||
}
|
||||
|
||||
render() {
|
||||
const { id } = this.props;
|
||||
const { todos } = this.context.getState();
|
||||
const dispatch = this.context.dispatch;
|
||||
|
||||
const item = todos[id];
|
||||
|
||||
return (
|
||||
<Stack horizontal verticalAlign="center" horizontalAlign="space-between">
|
||||
{!this.state.editing && (
|
||||
<>
|
||||
<Checkbox label={item.label} checked={item.completed} onChange={() => dispatch(actions.complete(id))} />
|
||||
<div>
|
||||
<IconButton iconProps={{ iconName: 'Edit' }} onClick={this.onEdit} />
|
||||
<IconButton iconProps={{ iconName: 'Cancel' }} onClick={() => dispatch(actions.remove(id))} />
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{this.state.editing && (
|
||||
<Stack.Item grow>
|
||||
<Stack horizontal gap={10}>
|
||||
<Stack.Item grow>
|
||||
<TextField value={this.state.editLabel} onChange={this.onChange} />
|
||||
</Stack.Item>
|
||||
<DefaultButton onClick={this.onDoneEdit}>Save</DefaultButton>
|
||||
</Stack>
|
||||
</Stack.Item>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
private onEdit = () => {
|
||||
const { id } = this.props;
|
||||
const { todos } = this.context.getState();
|
||||
const { label } = todos[id];
|
||||
|
||||
this.setState({
|
||||
editing: true,
|
||||
editLabel: this.state.editLabel || label
|
||||
});
|
||||
};
|
||||
|
||||
private onDoneEdit = () => {
|
||||
this.context.dispatch(actions.edit(this.props.id, this.state.editLabel));
|
||||
this.setState({
|
||||
editing: false,
|
||||
editLabel: undefined
|
||||
});
|
||||
};
|
||||
|
||||
private onChange = (evt: React.FormEvent<HTMLInputElement>, newValue: string) => {
|
||||
this.setState({ editLabel: newValue });
|
||||
};
|
||||
}
|
||||
|
||||
TodoListItem.contextType = StoreContext;
|
||||
@@ -1,16 +1,19 @@
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import { reducer } from './reducers';
|
||||
import { createStore } from 'redux';
|
||||
import { TodoApp } from './components/TodoApp';
|
||||
import { initializeIcons } from '@uifabric/icons';
|
||||
import { composeWithDevTools } from 'redux-devtools-extension';
|
||||
import { actions } from './actions';
|
||||
import { StoreContext } from 'redux-react-hook';
|
||||
|
||||
const store = createStore(reducer, {}, composeWithDevTools());
|
||||
|
||||
console.log(store.getState());
|
||||
initializeIcons();
|
||||
|
||||
// TODO: dispatch several actions and see the effects on state inside the Redux devtools
|
||||
|
||||
// store.dispatch(actions.???);
|
||||
// store.dispatch(actions.???);
|
||||
// store.dispatch(actions.???);
|
||||
|
||||
console.log(store.getState());
|
||||
ReactDOM.render(
|
||||
<StoreContext.Provider value={store}>
|
||||
<TodoApp />
|
||||
</StoreContext.Provider>,
|
||||
document.getElementById('app')
|
||||
);
|
||||
|
||||
@@ -1,27 +1,43 @@
|
||||
import { Store } from '../store';
|
||||
import { addTodo, remove, complete, clear } from './pureFunctions';
|
||||
import { combineReducers } from 'redux';
|
||||
import { createReducer } from 'redux-starter-kit';
|
||||
|
||||
function todoReducer(state: Store['todos'] = {}, action: any): Store['todos'] {
|
||||
switch (action.type) {
|
||||
case 'addTodo':
|
||||
return addTodo(state, action.id, action.label);
|
||||
export const todosReducer = createReducer<Store['todos']>(
|
||||
{},
|
||||
{
|
||||
addTodo(state, action) {
|
||||
state[action.id] = { label: action.label, completed: false };
|
||||
},
|
||||
|
||||
case 'remove':
|
||||
return remove(state, action.id);
|
||||
remove(state, action) {
|
||||
delete state[action.id];
|
||||
},
|
||||
|
||||
case 'clear':
|
||||
return clear(state);
|
||||
clear(state, action) {
|
||||
Object.keys(state).forEach(key => {
|
||||
if (state[key].completed) {
|
||||
delete state[key];
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
case 'complete':
|
||||
return complete(state, action.id);
|
||||
complete(state, action) {
|
||||
state[action.id].completed = !state[action.id].completed;
|
||||
},
|
||||
|
||||
edit(state, action) {
|
||||
state[action.id].label = action.label;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return state;
|
||||
}
|
||||
export const filterReducer = createReducer<Store['filter']>('all', {
|
||||
setFilter(state, action) {
|
||||
return action.filter;
|
||||
}
|
||||
});
|
||||
|
||||
export function reducer(state: Store, action: any): Store {
|
||||
return {
|
||||
todos: todoReducer(state.todos, action),
|
||||
filter: 'all'
|
||||
};
|
||||
}
|
||||
export const reducer = combineReducers({
|
||||
todos: todosReducer,
|
||||
filter: filterReducer
|
||||
});
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
import { addTodo, complete } from './pureFunctions';
|
||||
import { Store } from '../store';
|
||||
|
||||
describe('TodoApp reducers', () => {
|
||||
it('can add an item', () => {
|
||||
const state = <Store['todos']>{};
|
||||
|
||||
const newState = addTodo(state, '0', 'item1');
|
||||
|
||||
const keys = Object.keys(newState);
|
||||
|
||||
expect(newState).not.toBe(state);
|
||||
expect(keys.length).toBe(1);
|
||||
expect(newState[keys[0]].label).toBe('item1');
|
||||
expect(newState[keys[0]].completed).toBeFalsy();
|
||||
});
|
||||
|
||||
it('can complete an item', () => {
|
||||
const state = <Store['todos']>{};
|
||||
|
||||
let newState = addTodo(state, '0', 'item1');
|
||||
|
||||
const key = Object.keys(newState)[0];
|
||||
|
||||
newState = complete(newState, key);
|
||||
|
||||
expect(newState[key].completed).toBeTruthy();
|
||||
});
|
||||
});
|
||||
@@ -1,35 +0,0 @@
|
||||
import { Store, FilterTypes } from '../store';
|
||||
|
||||
export function addTodo(state: Store['todos'], id: string, label: string): Store['todos'] {
|
||||
return { ...state, [id]: { label, completed: false } };
|
||||
}
|
||||
|
||||
export function remove(state: Store['todos'], id: string) {
|
||||
const newTodos = { ...state };
|
||||
|
||||
delete newTodos[id];
|
||||
|
||||
return newTodos;
|
||||
}
|
||||
|
||||
export function complete(state: Store['todos'], id: string) {
|
||||
// Clone the todo, overriding
|
||||
const newTodo = { ...state[id], completed: !state[id].completed };
|
||||
return { ...state, [id]: newTodo };
|
||||
}
|
||||
|
||||
export function clear(state: Store['todos']) {
|
||||
const newTodos = { ...state };
|
||||
|
||||
Object.keys(state).forEach(key => {
|
||||
if (state[key].completed) {
|
||||
delete newTodos[key];
|
||||
}
|
||||
});
|
||||
|
||||
return newTodos;
|
||||
}
|
||||
|
||||
export function setFilter(state: Store['filter'], filter: FilterTypes) {
|
||||
return filter;
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import { createStore } from 'redux';
|
||||
import { reducer } from '.';
|
||||
import { actions } from '../actions';
|
||||
|
||||
describe('reducers', () => {
|
||||
it('should add items', () => {
|
||||
// 1. Use Redux's createStore() to create a store. Pass in a reducer along with the initial state.
|
||||
//
|
||||
// 2. Call store.dispatch() with some action messages to indicate the kind of
|
||||
// action to perform (in this case, addTodo)
|
||||
//
|
||||
// 3. Assert with expect() on the resultant store.getState().todos
|
||||
});
|
||||
|
||||
// Tests left for you to write:
|
||||
// - remove
|
||||
// - clear
|
||||
// - complete
|
||||
});
|
||||
Reference in New Issue
Block a user