Skip to content

Instantly share code, notes, and snippets.

@dpkreativ
Created February 25, 2022 09:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dpkreativ/25f42715db4da07262c988bf633cd192 to your computer and use it in GitHub Desktop.
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
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;
@Adityachoudhari1713
Copy link

awesome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment