fabiobiondi

React / TS simple CRUD

Sep 18th, 2020 (edited)
385
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // SIMPLE CRUD
  2. import React, { FormEvent, useEffect, useState } from 'react';
  3. import './App.css';
  4. import Axios from 'axios';
  5. import { Friend } from './model/friend';
  6.  
  7. function App() {
  8.   const [friends, setFriends] = useState<Friend[]>([])
  9.   const [friend, setFriend] = useState<Partial<Friend>>({ name: '' })
  10.  
  11.   useEffect(() => {
  12.     Axios.get<Friend[]>('http://localhost:3001/friends')
  13.       .then(res => setFriends(res.data))
  14.   }, [])
  15.  
  16.   function deleteHandler(id: number) {
  17.     Axios.delete(`http://localhost:3001/friends/${id}`)
  18.       .then(() => setFriends(friends.filter(f => f.id !== id)))
  19.   }
  20.  
  21.   function saveHandler(event: FormEvent<HTMLFormElement>) {
  22.     event.preventDefault();
  23.     if (friend.id) {
  24.       editHandler()
  25.     } else {
  26.       addHandler()
  27.     }
  28.   }
  29.  
  30.   function editHandler() {
  31.     Axios.patch<Friend>(`http://localhost:3001/friends/${friend.id}`, friend)
  32.       .then(res => {
  33.         const newList = friends.map(f => {
  34.           return f.id === friend.id ? { ...f, ...friend } : f
  35.         });
  36.         setFriends(newList)
  37.       })
  38.   }
  39.   function addHandler() {
  40.     if (friend.name && friend.name.length < 2) return;
  41.     const newFriend: Partial<Friend> = { name: friend.name,  tweets: 0 }  ;
  42.     Axios.post<Friend>(`http://localhost:3001/friends/`, newFriend)
  43.       .then(res => setFriends([...friends, res.data]))
  44.   }
  45.  
  46.   const getTotal = () => friends.reduce((acc, friend) =>  acc + friend.tweets, 0)
  47.  
  48.   function setActiveFriend(friend: Friend) {
  49.     console.log(friend)
  50.     setFriend(friend)
  51.   }
  52.  
  53.   return <div className="container mt-2">
  54.     <pre>{JSON.stringify(friend)}</pre>
  55.     {/* FORM */}
  56.     <form onSubmit={saveHandler}>
  57.       <input
  58.        type="text"
  59.        value={friend.name}
  60.        onChange={e => setFriend({ ...friend,name: e.currentTarget.value })}
  61.       />
  62.     </form>
  63.  
  64.     {/* LIST */}
  65.     {
  66.       friends.map((f, index) => (
  67.           <li className="list-group-item" key={f.id} onClick={() => setActiveFriend(f)}>
  68.             {index+1}. {f.name}
  69.             <i className="fa fa-trash pull-right" onClick={() => deleteHandler(f.id)} />
  70.           </li>
  71.         )
  72.       )
  73.     }
  74.  
  75.     <h1>Total: {getTotal()}</h1>
  76.   </div>
  77. }
  78.  
  79. export default App;
  80.  
  81.  
  82.  
  83. // server/db.json
  84. {
  85.   "friends": [
  86.     {
  87.       "id": 11,
  88.       "name": "fabio",
  89.       "tweets": 1000
  90.     },
  91.     {
  92.       "id": 22,
  93.       "name": "Lorenza",
  94.       "tweets": 10
  95.     }
  96.   ]
  97. }
  98.  
  99. // model/friend.ts
  100. export interface Friend {
  101.   id: number;
  102.   name: string;
  103.   tweets: number;
  104. }
  105.  
Add Comment
Please, Sign In to add comment