fixing up react-redux for all demo examples

This commit is contained in:
Ken
2019-03-03 09:49:43 -08:00
parent 27bf77b34f
commit 21a61f2450
15 changed files with 179 additions and 72 deletions

View File

@@ -132,7 +132,7 @@
</div> </div>
</li> </li>
<li class="Tile Tile--numbered"> <li class="Tile Tile--numbered">
<a target="_blank" href="./step2-07/" class="Tile-link"> <a target="_blank" href="./step2-07/demo/" class="Tile-link">
Redux: Service Calls Redux: Service Calls
</a> </a>
</li> </li>

5
package-lock.json generated
View File

@@ -8527,11 +8527,6 @@
"json-stringify-safe": "^5.0.1" "json-stringify-safe": "^5.0.1"
} }
}, },
"redux-react-hook": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/redux-react-hook/-/redux-react-hook-3.2.0.tgz",
"integrity": "sha512-GibqTO/Cgl2nRuhw2wacyfd2Nds8pYAPU/eYuTqXZ9v01CT7s7LSwDfPdtQua7TBqE8XNjrwKZqfDyEtfXt7vQ=="
},
"redux-starter-kit": { "redux-starter-kit": {
"version": "0.4.3", "version": "0.4.3",
"resolved": "https://registry.npmjs.org/redux-starter-kit/-/redux-starter-kit-0.4.3.tgz", "resolved": "https://registry.npmjs.org/redux-starter-kit/-/redux-starter-kit-0.4.3.tgz",

View File

@@ -2,7 +2,7 @@
[Lessons](../) | [Exercise](./exercise/) | [Demo](./demo/) [Lessons](../) | [Exercise](./exercise/) | [Demo](./demo/)
If you still have the app running from a previous step, stop it with `ctrl+c`. Start the tests instead by running `npm test` from the root of the `frontend-bootcamp` folder. If you don't already have the app running, start it by running `npm start` from the root of the `frontend-bootcamp` folder. Click the "exercise" link under day 2 step 5 to see results.
1. First, take a look at the store interface in `exercise/src/store/index.ts`. Note that the `Store` interface has two keys: `todos` and `filter`. We'll concentrate on `todos`, which is an object where the keys are string IDs and the values are of a `TodoItem` type. 1. First, take a look at the store interface in `exercise/src/store/index.ts`. Note that the `Store` interface has two keys: `todos` and `filter`. We'll concentrate on `todos`, which is an object where the keys are string IDs and the values are of a `TodoItem` type.

View File

@@ -1,7 +1,6 @@
import React from 'react'; import React from 'react';
import { Stack, Checkbox, IconButton, TextField, DefaultButton } from 'office-ui-fabric-react'; import { Stack, Checkbox, IconButton, TextField, DefaultButton } from 'office-ui-fabric-react';
import { actions } from '../actions'; import { actions } from '../actions';
import { StoreContext } from 'redux-react-hook';
import { Store } from '../store'; import { Store } from '../store';
import { connect } from 'react-redux'; import { connect } from 'react-redux';
@@ -69,7 +68,7 @@ class TodoListItem extends React.Component<TodoListItemProps, TodoListItemState>
}; };
private onDoneEdit = () => { private onDoneEdit = () => {
this.context.dispatch(actions.edit(this.props.id, this.state.editLabel)); this.props.edit(this.props.id, this.state.editLabel);
this.setState({ this.setState({
editing: false, editing: false,
editLabel: undefined editLabel: undefined

View File

@@ -2,16 +2,20 @@
[Lessons](../) | [Exercise](./exercise/) | [Demo](./demo/) [Lessons](../) | [Exercise](./exercise/) | [Demo](./demo/)
## Bind Redux Store with Class Component If you haven't arStart the app by running `npm start` from the root of the `frontend-bootcamp` folder. Click the "exercise" link under day 2 step 6 to see results.
1. Open `exercise/src/components/TodoHeader.tsx`. At the beginning of this exercise, the "Add" and "Clear Completed" buttons do not work. We'll be fixing that in this step!
2. Just like the 2.4 exercise, implement `onAdd` and `onFilter` using `this.context.dispatch()` calls to dispatch actions. 1. Open `exercise/src/index.tsx` and wrap `<TodoApp>` with `<Provider>` as instructed in the comment
## Bind Redux Store with Functional Component 2. Open `exercise/src/components/TodoFooter.tsx` and erase the "nullable" type modifier (i.e. the ?) in the interface definition of `TodoFooterProps`
1. Open `exercise/src/components/TodoFooter.tsx`. 3. Uncomment the bottom bits of code and fill in `connect()` arguments - feel free to use `TodoListItem.tsx` as a guide
2. Follow the instructions in the file to replace the `todos` const using the `useMappedState()` hook. 4. Repeat steps 2, 3 for the `TodoHeader.tsx` file
3. Retrieve the dispatch function with `useDispatch()` hook. ## Bonus exercise
For further reading, go here to learn more about the `mergeProps` and `options` parameters to `connect()`:
https://react-redux.js.org/api/connect

View File

@@ -1,15 +1,18 @@
import React from 'react'; import React from 'react';
import { DefaultButton, Stack, Text } from 'office-ui-fabric-react'; import { DefaultButton, Stack, Text } from 'office-ui-fabric-react';
import { actions } from '../actions'; import { actions } from '../actions';
import { useMappedState, useDispatch } from 'redux-react-hook'; import { connect } from 'react-redux';
import { Store } from '../store';
export const TodoFooter = () => { // TODO: these ?'s after the keys of an interface makes it optional
// TODO: make use of useMappedState(state => state) and the useDispatch functions to get // and can be removed when you finished connecting this component
// the Redux store and dispatching actions interface TodoFooterProps {
// HINT: const { todos } = useMappedState(...); todos?: Store['todos'];
// HINT: useDispatch() here too. clear?: () => void;
const todos = {}; }
const dispatch = (...args: any[]) => {};
const TodoFooter = (props: TodoFooterProps) => {
const { todos, clear } = props;
const itemCount = Object.keys(todos).filter(id => !todos[id].completed).length; const itemCount = Object.keys(todos).filter(id => !todos[id].completed).length;
@@ -18,7 +21,23 @@ export const TodoFooter = () => {
<Text> <Text>
{itemCount} item{itemCount === 1 ? '' : 's'} left {itemCount} item{itemCount === 1 ? '' : 's'} left
</Text> </Text>
<DefaultButton onClick={() => dispatch(actions.clear())}>Clear Completed</DefaultButton> <DefaultButton onClick={() => clear()}>Clear Completed</DefaultButton>
</Stack> </Stack>
); );
}; };
// TODO: write out the mapping functions for state and dispatch functions
/*
HINT: you can get started by copy pasting below code as arguments to connect()
(state: Store) => ({
// TODO: mapping for state
// HINT: look at what the component needed from the props interface
}),
dispatch => ({
// TODO: mapping for dispatch actions
// HINT: look at what the component needed from the props interface
})
*/
const ConnectedTodoFooter = connect()(TodoFooter);
export { ConnectedTodoFooter as TodoFooter };

View File

@@ -2,14 +2,21 @@ import React from 'react';
import { Stack, Text, Pivot, PivotItem, TextField, PrimaryButton } from 'office-ui-fabric-react'; import { Stack, Text, Pivot, PivotItem, TextField, PrimaryButton } from 'office-ui-fabric-react';
import { FilterTypes } from '../store'; import { FilterTypes } from '../store';
import { actions } from '../actions'; import { actions } from '../actions';
import { StoreContext } from 'redux-react-hook'; import { connect } from 'react-redux';
// TODO: these ?'s after the keys of an interface makes it optional
// and can be removed when you finished connecting this component
interface TodoHeaderProps {
addTodo?: (label: string) => void;
setFilter?: (filter: FilterTypes) => void;
}
interface TodoHeaderState { interface TodoHeaderState {
labelInput: string; labelInput: string;
} }
export class TodoHeader extends React.Component<{}, TodoHeaderState> { class TodoHeader extends React.Component<TodoHeaderProps, TodoHeaderState> {
constructor(props: {}) { constructor(props: TodoHeaderProps) {
super(props); super(props);
this.state = { labelInput: undefined }; this.state = { labelInput: undefined };
} }
@@ -49,8 +56,7 @@ export class TodoHeader extends React.Component<{}, TodoHeaderState> {
} }
private onAdd = () => { private onAdd = () => {
// TODO: Fill in a dispatch call to add the todo item this.props.addTodo(this.state.labelInput);
// HINT: this.context.dispatch(...);
this.setState({ labelInput: undefined }); this.setState({ labelInput: undefined });
}; };
@@ -59,9 +65,22 @@ export class TodoHeader extends React.Component<{}, TodoHeaderState> {
}; };
private onFilter = (item: PivotItem) => { private onFilter = (item: PivotItem) => {
// TODO: Fill in the dispatch call to set the filter this.props.setFilter(item.props.headerText as FilterTypes);
// HINT: this.context.dispatch(...);
}; };
} }
// TODO: set the context type of this Class to StoreContext // TODO: write out the mapping functions for state and dispatch functions
/*
HINT: you can get started by copy pasting below code as arguments to connect()
(state: Store) => ({
// TODO: mapping for state
// HINT: look at what the component needed from the props interface
}),
dispatch => ({
// TODO: mapping for dispatch actions
// HINT: look at what the component needed from the props interface
})
*/
const ConnectedTodoHeader = connect()(TodoHeader);
export { ConnectedTodoHeader as TodoHeader };

View File

@@ -1,10 +1,16 @@
import React from 'react'; import React from 'react';
import { Stack } from 'office-ui-fabric-react'; import { Stack } from 'office-ui-fabric-react';
import { TodoListItem } from './TodoListItem'; import { TodoListItem } from './TodoListItem';
import { useMappedState } from 'redux-react-hook'; import { connect } from 'react-redux';
import { Store } from '../store';
export const TodoList = () => { interface TodoListProps {
const { filter, todos } = useMappedState(state => state); todos: Store['todos'];
filter: Store['filter'];
}
const TodoList = (props: TodoListProps) => {
const { filter, todos } = props;
const filteredTodos = Object.keys(todos).filter(id => { const filteredTodos = Object.keys(todos).filter(id => {
return filter === 'all' || (filter === 'completed' && todos[id].completed) || (filter === 'active' && !todos[id].completed); return filter === 'all' || (filter === 'completed' && todos[id].completed) || (filter === 'active' && !todos[id].completed);
}); });
@@ -17,3 +23,6 @@ export const TodoList = () => {
</Stack> </Stack>
); );
}; };
const ConnectedTodoList = connect((state: Store) => ({ ...state }))(TodoList);
export { ConnectedTodoList as TodoList };

View File

@@ -1,10 +1,15 @@
import React from 'react'; import React from 'react';
import { Stack, Checkbox, IconButton, TextField, DefaultButton } from 'office-ui-fabric-react'; import { Stack, Checkbox, IconButton, TextField, DefaultButton } from 'office-ui-fabric-react';
import { actions } from '../actions'; import { actions } from '../actions';
import { StoreContext } from 'redux-react-hook'; import { Store } from '../store';
import { connect } from 'react-redux';
interface TodoListItemProps { interface TodoListItemProps {
id: string; id: string;
todos: Store['todos'];
complete: (id: string) => void;
remove: (id: string) => void;
edit: (id: string, label: string) => void;
} }
interface TodoListItemState { interface TodoListItemState {
@@ -12,7 +17,7 @@ interface TodoListItemState {
editLabel: string; editLabel: string;
} }
export class TodoListItem extends React.Component<TodoListItemProps, TodoListItemState> { class TodoListItem extends React.Component<TodoListItemProps, TodoListItemState> {
constructor(props: TodoListItemProps) { constructor(props: TodoListItemProps) {
super(props); super(props);
this.state = { editing: false, editLabel: undefined }; this.state = { editing: false, editLabel: undefined };
@@ -63,7 +68,7 @@ export class TodoListItem extends React.Component<TodoListItemProps, TodoListIte
}; };
private onDoneEdit = () => { private onDoneEdit = () => {
this.context.dispatch(actions.edit(this.props.id, this.state.editLabel)); this.props.edit(this.props.id, this.state.editLabel);
this.setState({ this.setState({
editing: false, editing: false,
editLabel: undefined editLabel: undefined
@@ -75,4 +80,13 @@ export class TodoListItem extends React.Component<TodoListItemProps, TodoListIte
}; };
} }
TodoListItem.contextType = StoreContext; const ConnectedTodoListItem = connect(
(state: Store) => ({ todos: state.todos }),
dispatch => ({
complete: label => dispatch(actions.addTodo(label)),
remove: label => dispatch(actions.addTodo(label)),
edit: filter => dispatch(actions.setFilter(filter))
})
)(TodoListItem);
export { ConnectedTodoListItem as TodoListItem };

View File

@@ -5,15 +5,11 @@ import { createStore } from 'redux';
import { TodoApp } from './components/TodoApp'; import { TodoApp } from './components/TodoApp';
import { initializeIcons } from '@uifabric/icons'; import { initializeIcons } from '@uifabric/icons';
import { composeWithDevTools } from 'redux-devtools-extension'; import { composeWithDevTools } from 'redux-devtools-extension';
import { StoreContext } from 'redux-react-hook'; // TODO: import { Provider } from 'react-redux';
const store = createStore(reducer, {}, composeWithDevTools()); const store = createStore(reducer, {}, composeWithDevTools());
initializeIcons(); initializeIcons();
ReactDOM.render( // TODO: wrap the <TodoApp> component with a <Provider store={store}> component
<StoreContext.Provider value={store}> ReactDOM.render(<TodoApp />, document.getElementById('app'));
<TodoApp />
</StoreContext.Provider>,
document.getElementById('app')
);

View File

@@ -1,11 +1,16 @@
import React from 'react'; import React from 'react';
import { DefaultButton, Stack, Text } from 'office-ui-fabric-react'; import { DefaultButton, Stack, Text } from 'office-ui-fabric-react';
import { actionsWithService } from '../actions'; import { actionsWithService } from '../actions';
import { useMappedState, useDispatch } from 'redux-react-hook'; import { connect } from 'react-redux';
import { Store } from '../store';
export const TodoFooter = () => { interface TodoFooterProps {
const { todos } = useMappedState(state => state); todos: Store['todos'];
const dispatch = useDispatch(); clear: () => void;
}
const TodoFooter = (props: TodoFooterProps) => {
const { todos, clear } = props;
const itemCount = Object.keys(todos).filter(id => !todos[id].completed).length; const itemCount = Object.keys(todos).filter(id => !todos[id].completed).length;
@@ -14,7 +19,18 @@ export const TodoFooter = () => {
<Text> <Text>
{itemCount} item{itemCount === 1 ? '' : 's'} left {itemCount} item{itemCount === 1 ? '' : 's'} left
</Text> </Text>
<DefaultButton onClick={() => dispatch(actionsWithService.clear())}>Clear Completed</DefaultButton> <DefaultButton onClick={() => clear()}>Clear Completed</DefaultButton>
</Stack> </Stack>
); );
}; };
const ConnectedTodoFooter = connect(
(state: Store) => ({
todos: state.todos
}),
(dispatch: any) => ({
clear: () => dispatch(actionsWithService.clear())
})
)(TodoFooter);
export { ConnectedTodoFooter as TodoFooter };

View File

@@ -1,15 +1,20 @@
import React from 'react'; import React from 'react';
import { Stack, Text, Pivot, PivotItem, TextField, PrimaryButton } from 'office-ui-fabric-react'; import { Stack, Text, Pivot, PivotItem, TextField, PrimaryButton } from 'office-ui-fabric-react';
import { FilterTypes } from '../store'; import { FilterTypes } from '../store';
import { actionsWithService, actions } from '../actions'; import { actions, actionsWithService } from '../actions';
import { StoreContext } from 'redux-react-hook'; import { connect } from 'react-redux';
interface TodoHeaderProps {
addTodo: (label: string) => void;
setFilter: (filter: FilterTypes) => void;
}
interface TodoHeaderState { interface TodoHeaderState {
labelInput: string; labelInput: string;
} }
export class TodoHeader extends React.Component<{}, TodoHeaderState> { class TodoHeader extends React.Component<TodoHeaderProps, TodoHeaderState> {
constructor(props: {}) { constructor(props: TodoHeaderProps) {
super(props); super(props);
this.state = { labelInput: undefined }; this.state = { labelInput: undefined };
} }
@@ -49,7 +54,7 @@ export class TodoHeader extends React.Component<{}, TodoHeaderState> {
} }
private onAdd = () => { private onAdd = () => {
this.context.dispatch(actionsWithService.addTodo(this.state.labelInput)); this.props.addTodo(this.state.labelInput);
this.setState({ labelInput: undefined }); this.setState({ labelInput: undefined });
}; };
@@ -58,8 +63,16 @@ export class TodoHeader extends React.Component<{}, TodoHeaderState> {
}; };
private onFilter = (item: PivotItem) => { private onFilter = (item: PivotItem) => {
this.context.dispatch(actions.setFilter(item.props.headerText as FilterTypes)); this.props.setFilter(item.props.headerText as FilterTypes);
}; };
} }
TodoHeader.contextType = StoreContext; const ConnectedTodoHeader = connect(
state => {},
(dispatch: any) => ({
addTodo: label => dispatch(actionsWithService.addTodo(label)),
setFilter: filter => dispatch(actions.setFilter(filter))
})
)(TodoHeader);
export { ConnectedTodoHeader as TodoHeader };

View File

@@ -1,10 +1,16 @@
import React from 'react'; import React from 'react';
import { Stack } from 'office-ui-fabric-react'; import { Stack } from 'office-ui-fabric-react';
import { TodoListItem } from './TodoListItem'; import { TodoListItem } from './TodoListItem';
import { useMappedState } from 'redux-react-hook'; import { connect } from 'react-redux';
import { Store } from '../store';
export const TodoList = () => { interface TodoListProps {
const { filter, todos } = useMappedState(state => state); todos: Store['todos'];
filter: Store['filter'];
}
const TodoList = (props: TodoListProps) => {
const { filter, todos } = props;
const filteredTodos = Object.keys(todos).filter(id => { const filteredTodos = Object.keys(todos).filter(id => {
return filter === 'all' || (filter === 'completed' && todos[id].completed) || (filter === 'active' && !todos[id].completed); return filter === 'all' || (filter === 'completed' && todos[id].completed) || (filter === 'active' && !todos[id].completed);
}); });
@@ -17,3 +23,6 @@ export const TodoList = () => {
</Stack> </Stack>
); );
}; };
const ConnectedTodoList = connect((state: Store) => ({ ...state }))(TodoList);
export { ConnectedTodoList as TodoList };

View File

@@ -1,10 +1,15 @@
import React from 'react'; import React from 'react';
import { Stack, Checkbox, IconButton, TextField, DefaultButton } from 'office-ui-fabric-react'; import { Stack, Checkbox, IconButton, TextField, DefaultButton } from 'office-ui-fabric-react';
import { actionsWithService } from '../actions'; import { actions, actionsWithService } from '../actions';
import { StoreContext } from 'redux-react-hook'; import { Store } from '../store';
import { connect } from 'react-redux';
interface TodoListItemProps { interface TodoListItemProps {
id: string; id: string;
todos: Store['todos'];
complete: (id: string) => void;
remove: (id: string) => void;
edit: (id: string, label: string) => void;
} }
interface TodoListItemState { interface TodoListItemState {
@@ -12,7 +17,7 @@ interface TodoListItemState {
editLabel: string; editLabel: string;
} }
export class TodoListItem extends React.Component<TodoListItemProps, TodoListItemState> { class TodoListItem extends React.Component<TodoListItemProps, TodoListItemState> {
constructor(props: TodoListItemProps) { constructor(props: TodoListItemProps) {
super(props); super(props);
this.state = { editing: false, editLabel: undefined }; this.state = { editing: false, editLabel: undefined };
@@ -29,10 +34,10 @@ export class TodoListItem extends React.Component<TodoListItemProps, TodoListIte
<Stack horizontal verticalAlign="center" horizontalAlign="space-between"> <Stack horizontal verticalAlign="center" horizontalAlign="space-between">
{!this.state.editing && ( {!this.state.editing && (
<> <>
<Checkbox label={item.label} checked={item.completed} onChange={() => dispatch(actionsWithService.complete(id))} /> <Checkbox label={item.label} checked={item.completed} onChange={() => dispatch(actions.complete(id))} />
<div> <div>
<IconButton iconProps={{ iconName: 'Edit' }} onClick={this.onEdit} /> <IconButton iconProps={{ iconName: 'Edit' }} onClick={this.onEdit} />
<IconButton iconProps={{ iconName: 'Cancel' }} onClick={() => dispatch(actionsWithService.remove(id))} /> <IconButton iconProps={{ iconName: 'Cancel' }} onClick={() => dispatch(actions.remove(id))} />
</div> </div>
</> </>
)} )}
@@ -63,7 +68,7 @@ export class TodoListItem extends React.Component<TodoListItemProps, TodoListIte
}; };
private onDoneEdit = () => { private onDoneEdit = () => {
this.context.dispatch(actionsWithService.edit(this.props.id, this.state.editLabel)); this.props.edit(this.props.id, this.state.editLabel);
this.setState({ this.setState({
editing: false, editing: false,
editLabel: undefined editLabel: undefined
@@ -75,4 +80,13 @@ export class TodoListItem extends React.Component<TodoListItemProps, TodoListIte
}; };
} }
TodoListItem.contextType = StoreContext; const ConnectedTodoListItem = connect(
(state: Store) => ({ todos: state.todos }),
(dispatch: any) => ({
complete: label => dispatch(actionsWithService.addTodo(label)),
remove: label => dispatch(actionsWithService.addTodo(label)),
edit: filter => dispatch(actions.setFilter(filter))
})
)(TodoListItem);
export { ConnectedTodoListItem as TodoListItem };

View File

@@ -3,9 +3,9 @@ import ReactDOM from 'react-dom';
import { reducer } from './reducers'; import { reducer } from './reducers';
import { createStore, applyMiddleware } from 'redux'; import { createStore, applyMiddleware } from 'redux';
import { TodoApp } from './components/TodoApp'; import { TodoApp } from './components/TodoApp';
import { Provider } from 'react-redux';
import { initializeIcons } from '@uifabric/icons'; import { initializeIcons } from '@uifabric/icons';
import { composeWithDevTools } from 'redux-devtools-extension'; import { composeWithDevTools } from 'redux-devtools-extension';
import { StoreContext } from 'redux-react-hook';
import thunk from 'redux-thunk'; import thunk from 'redux-thunk';
import { FilterTypes } from './store'; import { FilterTypes } from './store';
@@ -22,9 +22,9 @@ import { FilterTypes } from './store';
initializeIcons(); initializeIcons();
ReactDOM.render( ReactDOM.render(
<StoreContext.Provider value={store}> <Provider store={store}>
<TodoApp /> <TodoApp />
</StoreContext.Provider>, </Provider>,
document.getElementById('app') document.getElementById('app')
); );
})(); })();