Skip to content

Commit ecd2919

Browse files
committed
using array.with instead of slicing
1 parent e6dc12e commit ecd2919

File tree

2 files changed

+15
-8
lines changed

2 files changed

+15
-8
lines changed

react/core/02-state/lecture/GroceryForm.tsx

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ export function GroceryForm({ onSubmit }: Props) {
1919
// 1. new FormData
2020
// 2. Scrape for it: ids (bad) refs (good)
2121
// 3. Controlled with state
22+
23+
onSubmit({ name: 'test', quantity: 1 })
2224
}
2325

2426
return (

react/core/02-state/lecture/index.tsx

Lines changed: 13 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -19,17 +19,22 @@ function App() {
1919
{ id: 3, name: 'Tomatoes', quantity: 3 },
2020
])
2121

22-
function addItem(item: Item) {}
22+
function addItem(item: Item) {
23+
// Add item to items array
24+
}
2325

2426
// Without Cloning (Faster, More Difficult)
2527
function subtractQuantity(id: number) {
26-
const index = items.findIndex((item) => item.id === id)
27-
const newItem = { ...items[index], quantity: items[index].quantity - 1 }
28-
if (newItem.quantity === 0) {
29-
setItems([...items.slice(0, index), ...items.slice(index + 1)])
30-
} else {
31-
setItems([...items.slice(0, index), newItem, ...items.slice(index + 1)])
32-
}
28+
// const index = items.findIndex((item) => item.id === id)
29+
// const newItem = { ...items[index], quantity: items[index].quantity - 1 }
30+
// OLD WAY
31+
// if (newItem.quantity === 0) {
32+
// setItems([...items.slice(0, index), ...items.slice(index + 1)])
33+
// } else {
34+
// setItems([...items.slice(0, index), newItem, ...items.slice(index + 1)])
35+
// }
36+
// NEW WAY
37+
// setItems(items.with(index, newItem))
3338
}
3439

3540
// With Cloning (Slower, Easier)

0 commit comments

Comments
 (0)