11import React , { useReducer } from 'react' ;
22import styled from 'styled-components' ;
3+ import { makeId } from 'simple-util-js' ;
34
45import CartInput from './CartInput' ;
56import CartShow from './CartShow' ;
@@ -10,7 +11,7 @@ const reducer = (state, { type, payload }) => {
1011 switch ( type ) {
1112 case 'INCREMENT' :
1213 return state . map ( item => {
13- if ( item . id === payload . id ) {
14+ if ( item . id === payload ) {
1415 item . quantity = item . quantity + 1 ;
1516 return item ;
1617 }
@@ -19,8 +20,8 @@ const reducer = (state, { type, payload }) => {
1920 } ) ;
2021 case 'DECREMENT' :
2122 return state . map ( item => {
22- if ( item . id === payload . id ) {
23- item . quantity = item . quantity - 1 ;
23+ if ( item . id === payload ) {
24+ item . quantity = item . quantity <= 0 ? 0 : item . quantity - 1 ;
2425 return item ;
2526 }
2627
@@ -30,9 +31,11 @@ const reducer = (state, { type, payload }) => {
3031 return [
3132 state ,
3233 {
33- payload
34+ ... payload
3435 }
3536 ] ;
37+ case 'DELETE' :
38+ return state . filter ( item => item . id !== payload ) ;
3639 default :
3740 throw new Error ( ) ;
3841 }
@@ -41,13 +44,13 @@ const reducer = (state, { type, payload }) => {
4144const App = ( ) => {
4245 const [ carts , dispatch ] = useReducer ( reducer , [
4346 {
44- id : 'test' ,
47+ id : makeId ( ) ,
4548 name : 'test' ,
4649 price : 10 ,
4750 quantity : 10
4851 } ,
4952 {
50- id : 'test2' ,
53+ id : makeId ( ) ,
5154 name : 'test2' ,
5255 price : 100 ,
5356 quantity : 4
@@ -56,7 +59,7 @@ const App = () => {
5659 return (
5760 < Wrapper >
5861 < CartInput dispatch = { dispatch } > </ CartInput >
59- < CartShow carts = { carts } > </ CartShow >
62+ < CartShow carts = { carts } dispatch = { dispatch } > </ CartShow >
6063 </ Wrapper >
6164 ) ;
6265} ;
0 commit comments