1- import React , { useState } from 'react' ;
1+ import React , { useState , useReducer } from 'react' ;
22import uuid from 'uuid/v4' ;
33
44const initalTodos = [
@@ -19,10 +19,52 @@ const initalTodos = [
1919 } ,
2020] ;
2121
22+ const filterReducer = ( state , action ) => {
23+ switch ( action . type ) {
24+ case 'SHOW_ALL' :
25+ return 'ALL' ;
26+ case 'SHOW_COMPLETE' :
27+ return 'COMPLETE' ;
28+ case 'SHOW_INCOMPLETE' :
29+ return 'INCOMPLETE' ;
30+ default :
31+ throw new Error ( ) ;
32+ }
33+ } ;
34+
2235const App = ( ) => {
36+ const [ filter , dispatchFilter ] = useReducer ( filterReducer , 'ALL' ) ;
2337 const [ todos , setTodos ] = useState ( initalTodos ) ;
2438 const [ task , setTask ] = useState ( '' ) ;
2539
40+ const handleShowAll = ( ) => {
41+ dispatchFilter ( { type : 'SHOW_ALL' } ) ;
42+ } ;
43+
44+ const handleShowComplete = ( ) => {
45+ dispatchFilter ( { type : 'SHOW_COMPLETE' } ) ;
46+ } ;
47+
48+ const handleShowIncomplete = ( ) => {
49+ dispatchFilter ( { type : 'SHOW_INCOMPLETE' } ) ;
50+ } ;
51+
52+ const filteredTodos = todos . filter ( todo => {
53+ if ( filter === 'ALL' ) {
54+ return true ;
55+ }
56+
57+ if ( filter === 'COMPLETE' && todo . complete ) {
58+ return true ;
59+ }
60+
61+ if ( filter === 'INCOMPLETE' && ! todo . complete ) {
62+ return true ;
63+ }
64+
65+ return false ;
66+ } ) ;
67+
2668 const handleChangeCheckbox = id => {
2769 setTodos (
2870 todos . map ( todo => {
@@ -51,8 +93,20 @@ const App = () => {
5193
5294 return (
5395 < div >
96+ < div >
97+ < button type = "button" onClick = { handleShowAll } >
98+ Show All
99+ </ button >
100+ < button type = "button" onClick = { handleShowComplete } >
101+ Show Complete
102+ </ button >
103+ < button type = "button" onClick = { handleShowIncomplete } >
104+ Show Incomplete
105+ </ button >
106+ </ div >
107+
54108 < ul >
55- { todos . map ( todo => (
109+ { filteredTodos . map ( todo => (
56110 < li key = { todo . id } >
57111 < label >
58112 < input
0 commit comments