|
| 1 | +/** |
| 2 | + * Example: ObjectAndArrayUpdates |
| 3 | + * What: Update nested structures immutably (object + array). |
| 4 | + * Why: React state must be treated as immutable to trigger correct re-renders. |
| 5 | + * Concepts: Spread syntax, map/filter, structural sharing. |
| 6 | + */ |
| 7 | +import { useState } from "react"; |
| 8 | + |
| 9 | +type Todo = { id: string; text: string; done: boolean }; |
| 10 | +type User = { name: string; city: string }; |
| 11 | + |
| 12 | +export default function ObjectAndArrayUpdates() { |
| 13 | + // Object state: must create new object when updating |
| 14 | + const [user, setUser] = useState<User>({ name: "Ava", city: "Pune" }); |
| 15 | + |
| 16 | + // Array state: must create new array when updating |
| 17 | + const [todos, setTodos] = useState<Todo[]>([ |
| 18 | + { id: "1", text: "Learn useState", done: true }, |
| 19 | + { id: "2", text: "Practice examples", done: false }, |
| 20 | + ]); |
| 21 | + |
| 22 | + // Update object immutably: spread existing user, override city |
| 23 | + const moveCity = () => setUser(u => ({ ...u, city: "Bangalore" })); |
| 24 | + |
| 25 | + // Update array immutably: spread existing todos, add new item at end |
| 26 | + const addTodo = () => setTodos(ts => [...ts, { |
| 27 | + id: crypto.randomUUID(), |
| 28 | + text: "New item", |
| 29 | + done: false |
| 30 | + }]); |
| 31 | + |
| 32 | + // Update specific array item: map through, update matching id, keep others same |
| 33 | + const toggle = (id: string) => setTodos(ts => |
| 34 | + ts.map(t => (t.id === id ? { ...t, done: !t.done } : t)) |
| 35 | + ); |
| 36 | + |
| 37 | + // Remove array item: filter out the item with matching id |
| 38 | + const remove = (id: string) => setTodos(ts => ts.filter(t => t.id !== id)); |
| 39 | + |
| 40 | + return ( |
| 41 | + <div> |
| 42 | + {/* Display current user info */} |
| 43 | + <p>User: {user.name} — {user.city}</p> |
| 44 | + <button onClick={moveCity}>Move city</button> |
| 45 | + <hr /> |
| 46 | + <button onClick={addTodo}>Add todo</button> |
| 47 | + |
| 48 | + {/* Render each todo with toggle and remove functionality */} |
| 49 | + <ul> |
| 50 | + {todos.map(t => ( |
| 51 | + <li key={t.id}> |
| 52 | + <label> |
| 53 | + <input |
| 54 | + type="checkbox" |
| 55 | + checked={t.done} |
| 56 | + onChange={() => toggle(t.id)} |
| 57 | + /> |
| 58 | + {t.text} |
| 59 | + </label> |
| 60 | + <button onClick={() => remove(t.id)}>x</button> |
| 61 | + </li> |
| 62 | + ))} |
| 63 | + </ul> |
| 64 | + </div> |
| 65 | + ); |
| 66 | +} |
| 67 | + |
0 commit comments