Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // SIMPLE CRUD
- import React, { FormEvent, useEffect, useState } from 'react';
- import './App.css';
- import Axios from 'axios';
- import { Friend } from './model/friend';
- function App() {
- const [friends, setFriends] = useState<Friend[]>([])
- const [friend, setFriend] = useState<Partial<Friend>>({ name: '' })
- useEffect(() => {
- Axios.get<Friend[]>('http://localhost:3001/friends')
- .then(res => setFriends(res.data))
- }, [])
- function deleteHandler(id: number) {
- Axios.delete(`http://localhost:3001/friends/${id}`)
- .then(() => setFriends(friends.filter(f => f.id !== id)))
- }
- function saveHandler(event: FormEvent<HTMLFormElement>) {
- event.preventDefault();
- if (friend.id) {
- editHandler()
- } else {
- addHandler()
- }
- }
- function editHandler() {
- Axios.patch<Friend>(`http://localhost:3001/friends/${friend.id}`, friend)
- .then(res => {
- const newList = friends.map(f => {
- return f.id === friend.id ? { ...f, ...friend } : f
- });
- setFriends(newList)
- })
- }
- function addHandler() {
- if (friend.name && friend.name.length < 2) return;
- const newFriend: Partial<Friend> = { name: friend.name, tweets: 0 } ;
- Axios.post<Friend>(`http://localhost:3001/friends/`, newFriend)
- .then(res => setFriends([...friends, res.data]))
- }
- const getTotal = () => friends.reduce((acc, friend) => acc + friend.tweets, 0)
- function setActiveFriend(friend: Friend) {
- console.log(friend)
- setFriend(friend)
- }
- return <div className="container mt-2">
- <pre>{JSON.stringify(friend)}</pre>
- {/* FORM */}
- <form onSubmit={saveHandler}>
- <input
- type="text"
- value={friend.name}
- onChange={e => setFriend({ ...friend,name: e.currentTarget.value })}
- />
- </form>
- {/* LIST */}
- {
- friends.map((f, index) => (
- <li className="list-group-item" key={f.id} onClick={() => setActiveFriend(f)}>
- {index+1}. {f.name}
- <i className="fa fa-trash pull-right" onClick={() => deleteHandler(f.id)} />
- </li>
- )
- )
- }
- <h1>Total: {getTotal()}</h1>
- </div>
- }
- export default App;
- // server/db.json
- {
- "friends": [
- {
- "id": 11,
- "name": "fabio",
- "tweets": 1000
- },
- {
- "id": 22,
- "name": "Lorenza",
- "tweets": 10
- }
- ]
- }
- // model/friend.ts
- export interface Friend {
- id: number;
- name: string;
- tweets: number;
- }
Add Comment
Please, Sign In to add comment