Skip to content
Permalink
Browse files

filter with reducer

  • Loading branch information...
rwieruch committed Apr 6, 2019
1 parent 8f727ce commit 08d4b7130613eef209687f5f4c270c86716f1f09
Showing with 56 additions and 2 deletions.
  1. +56 −2 src/App.js
@@ -1,4 +1,4 @@
import React, { useState } from 'react';
import React, { useState, useReducer } from 'react';
import uuid from 'uuid/v4';

const initalTodos = [
@@ -19,10 +19,52 @@ const initalTodos = [
},
];

const filterReducer = (state, action) => {
switch (action.type) {
case 'SHOW_ALL':
return 'ALL';
case 'SHOW_COMPLETE':
return 'COMPLETE';
case 'SHOW_INCOMPLETE':
return 'INCOMPLETE';
default:
throw new Error();
}
};

const App = () => {
const [filter, dispatchFilter] = useReducer(filterReducer, 'ALL');
const [todos, setTodos] = useState(initalTodos);
const [task, setTask] = useState('');

const handleShowAll = () => {
dispatchFilter({ type: 'SHOW_ALL' });
};

const handleShowComplete = () => {
dispatchFilter({ type: 'SHOW_COMPLETE' });
};

const handleShowIncomplete = () => {
dispatchFilter({ type: 'SHOW_INCOMPLETE' });
};

const filteredTodos = todos.filter(todo => {
if (filter === 'ALL') {
return true;
}

if (filter === 'COMPLETE' && todo.complete) {
return true;
}

if (filter === 'INCOMPLETE' && !todo.complete) {
return true;
}

return false;
});

const handleChangeCheckbox = id => {
setTodos(
todos.map(todo => {
@@ -51,8 +93,20 @@ const App = () => {

return (
<div>
<div>
<button type="button" onClick={handleShowAll}>
Show All
</button>
<button type="button" onClick={handleShowComplete}>
Show Complete
</button>
<button type="button" onClick={handleShowIncomplete}>
Show Incomplete
</button>
</div>

<ul>
{todos.map(todo => (
{filteredTodos.map(todo => (
<li key={todo.id}>
<label>
<input

0 comments on commit 08d4b71

Please sign in to comment.
You can’t perform that action at this time.