@@ -68,33 +68,40 @@ const todoReducer = (state, action) => {
6868 }
6969} ;
7070
71- const App = ( ) => {
72- const [ filter , dispatchFilter ] = useReducer ( filterReducer , 'ALL' ) ;
73- const [ todos , dispatchTodos ] = useReducer (
74- todoReducer ,
75- initialTodos
71+ const useCombinedReducer = useReducers => {
72+ // Global State
73+ const state = Object . keys ( useReducers ) . reduce (
74+ ( acc , key ) => ( { ... acc , [ key ] : useReducers [ key ] [ 0 ] } ) ,
75+ { }
7676 ) ;
7777
7878 // Global Dispatch Function
7979 const dispatch = action =>
80- [ dispatchTodos , dispatchFilter ] . forEach ( fn => fn ( action ) ) ;
80+ Object . keys ( useReducers )
81+ . map ( key => useReducers [ key ] [ 1 ] )
82+ . forEach ( fn => fn ( action ) ) ;
8183
82- // Global State
83- const state = {
84- filter,
85- todos,
86- } ;
84+ return [ state , dispatch ] ;
85+ } ;
86+
87+ const App = ( ) => {
88+ const [ state , dispatch ] = useCombinedReducer ( {
89+ filter : useReducer ( filterReducer , 'ALL' ) ,
90+ todos : useReducer ( todoReducer , initialTodos ) ,
91+ } ) ;
92+
93+ const { filter, todos } = state ;
8794
88- const filteredTodos = state . todos . filter ( todo => {
89- if ( state . filter === 'ALL' ) {
95+ const filteredTodos = todos . filter ( todo => {
96+ if ( filter === 'ALL' ) {
9097 return true ;
9198 }
9299
93- if ( state . filter === 'COMPLETE' && todo . complete ) {
100+ if ( filter === 'COMPLETE' && todo . complete ) {
94101 return true ;
95102 }
96103
97- if ( state . filter === 'INCOMPLETE' && ! todo . complete ) {
104+ if ( filter === 'INCOMPLETE' && ! todo . complete ) {
98105 return true ;
99106 }
100107
0 commit comments