panku-app/src/pages/friends.jsx

1import { useState, useContext } from "react"; 2 3import PageTitle from "@/components/page-title"; 4import { AppContext } from "@/ContextProvider"; 5 6import { makeId } from "@/utils"; 7 8const Friends = () => { 9 const { state, dispatch } = useContext(AppContext); 10 11 // [{id: '123', name: 'Jake'}] 12 let defaultFriends = [ 13 { 14 id: makeId(), 15 name: "", 16 }, 17 ]; 18 if (state.friends.length > 0) { 19 defaultFriends = state.friends; 20 } 21 const [friends, setFriends] = useState(defaultFriends); 22 23 const updateFriendName = (idx, newName) => { 24 setFriends((prev) => { 25 const _friends = [...prev]; 26 _friends[idx] = { 27 id: _friends[idx]["id"], 28 name: newName, 29 }; 30 return _friends; 31 }); 32 }; 33 34 const addNewFriend = () => { 35 setFriends((prev) => { 36 const _friends = [...prev]; 37 _friends.push({ 38 id: makeId(), 39 name: "", 40 }); 41 return _friends; 42 }); 43 }; 44 45 const removeFriend = (idx) => { 46 setFriends((prev) => { 47 const _friends = [...prev]; 48 _friends.splice(idx, 1); 49 return _friends; 50 }); 51 }; 52 53 function handleSubmit(e) { 54 e.preventDefault(); 55 dispatch({ 56 type: "setFriends", 57 payload: friends, 58 }); 59 } 60 61 return ( 62 <> 63 <PageTitle title="friends" /> 64 65 <h1>friends</h1> 66 67 <form onSubmit={handleSubmit}> 68 <ol style={{ paddingLeft: "22px" }}> 69 {friends.map((f, idx) => ( 70 <li key={f.id}> 71 <input 72 type="text" 73 placeholder="Mythili" 74 value={f.name} 75 onChange={(e) => updateFriendName(idx, e.target.value)} 76 required 77 /> 78 {/* cant remove all friends */} 79 {friends.length > 1 && ( 80 <button 81 className="btn btn-text" 82 type="button" 83 onClick={() => removeFriend(idx)} 84 > 85 &minus; remove 86 </button> 87 )} 88 </li> 89 ))} 90 </ol> 91 92 <div className="text-right"> 93 <button className="btn" type="button" onClick={addNewFriend}> 94 &#43; add 95 </button> 96 </div> 97 98 <p></p> 99 <div className="text-center"> 100 <button className="btn" type="submit"> 101 update friends 102 </button> 103 </div> 104 </form> 105 </> 106 ); 107}; 108 109export default Friends;