Created
February 25, 2022 09:04
-
-
Save dpkreativ/25f42715db4da07262c988bf633cd192 to your computer and use it in GitHub Desktop.
Demonstrating how to implement useReducer to handle multiple states in a shopping cart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useReducer } from 'react'; | |
const ShoppingCart = () => { | |
const initialState = { | |
input: '', | |
items: [], | |
}; | |
const reducer = (state, action) => { | |
switch (action.type) { | |
case 'add': | |
let updatedState = { | |
...state, | |
items: [...state.items, action.payload], | |
}; | |
state.input = ''; | |
return updatedState; | |
case 'delete': | |
let filteredState = { | |
...state, | |
items: [...state.items].filter((x) => x.id !== action.payload), | |
}; | |
return filteredState; | |
case 'input': | |
return { | |
...state, | |
input: action.payload, | |
}; | |
default: | |
return state; | |
} | |
}; | |
const [state, dispatch] = useReducer(reducer, initialState); | |
const handleSubmit = (e) => { | |
e.preventDefault(); | |
dispatch({ | |
type: 'add', | |
payload: { | |
id: new Date().getTime(), | |
name: state.input, | |
}, | |
}); | |
}; | |
const handleChange = (e) => { | |
dispatch({ | |
type: 'input', | |
payload: e.target.value, | |
}); | |
}; | |
return ( | |
<div className="container"> | |
<h1>Shopping Cart</h1> | |
<form onSubmit={handleSubmit}> | |
<input type="text" value={state.input} onChange={handleChange} /> | |
</form> | |
<div> | |
{state && | |
state.items.map((item, index) => ( | |
<div key={index} className="flex"> | |
<div> | |
{index + 1}. {item.name} | |
</div> | |
<div> | |
<button | |
onClick={() => dispatch({ type: 'delete', payload: item.id })} | |
> | |
x | |
</button> | |
</div> | |
</div> | |
))} | |
</div> | |
</div> | |
); | |
}; | |
export default ShoppingCart; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
awesome