Skip to content

Commit

Permalink
dispatch all
Browse files Browse the repository at this point in the history
  • Loading branch information
rwieruch committed Apr 6, 2019
1 parent 9580679 commit 7f1cf96
Showing 1 changed file with 15 additions and 9 deletions.
24 changes: 15 additions & 9 deletions src/App.js
Expand Up @@ -6,7 +6,7 @@ import React, {
} from 'react'; } from 'react';
import uuid from 'uuid/v4'; import uuid from 'uuid/v4';


const TodoContext = createContext(null); const DispatchContext = createContext(null);


const initalTodos = [ const initalTodos = [
{ {
Expand Down Expand Up @@ -35,7 +35,7 @@ const filterReducer = (state, action) => {
case 'SHOW_INCOMPLETE': case 'SHOW_INCOMPLETE':
return 'INCOMPLETE'; return 'INCOMPLETE';
default: default:
throw new Error(); return state;
} }
}; };


Expand Down Expand Up @@ -64,14 +64,18 @@ const todoReducer = (state, action) => {
complete: false, complete: false,
}); });
default: default:
throw new Error(); return state;
} }
}; };


const App = () => { const App = () => {
const [filter, dispatchFilter] = useReducer(filterReducer, 'ALL'); const [filter, dispatchFilter] = useReducer(filterReducer, 'ALL');
const [todos, dispatchTodos] = useReducer(todoReducer, initalTodos); const [todos, dispatchTodos] = useReducer(todoReducer, initalTodos);


// Global Dispatch Function
const dispatch = action =>
[dispatchTodos, dispatchFilter].forEach(fn => fn(action));

const filteredTodos = todos.filter(todo => { const filteredTodos = todos.filter(todo => {
if (filter === 'ALL') { if (filter === 'ALL') {
return true; return true;
Expand All @@ -89,15 +93,17 @@ const App = () => {
}); });


return ( return (
<TodoContext.Provider value={dispatchTodos}> <DispatchContext.Provider value={dispatch}>
<Filter dispatch={dispatchFilter} /> <Filter />
<TodoList todos={filteredTodos} /> <TodoList todos={filteredTodos} />
<AddTodo /> <AddTodo />
</TodoContext.Provider> </DispatchContext.Provider>
); );
}; };


const Filter = ({ dispatch }) => { const Filter = () => {
const dispatch = useContext(DispatchContext);

const handleShowAll = () => { const handleShowAll = () => {
dispatch({ type: 'SHOW_ALL' }); dispatch({ type: 'SHOW_ALL' });
}; };
Expand Down Expand Up @@ -134,7 +140,7 @@ const TodoList = ({ todos }) => (
); );


const TodoItem = ({ todo }) => { const TodoItem = ({ todo }) => {
const dispatch = useContext(TodoContext); const dispatch = useContext(DispatchContext);


const handleChange = () => const handleChange = () =>
dispatch({ dispatch({
Expand All @@ -157,7 +163,7 @@ const TodoItem = ({ todo }) => {
}; };


const AddTodo = () => { const AddTodo = () => {
const dispatch = useContext(TodoContext); const dispatch = useContext(DispatchContext);


const [task, setTask] = useState(''); const [task, setTask] = useState('');


Expand Down

0 comments on commit 7f1cf96

Please sign in to comment.