xây dựng handleDeleteClick (ok)

C:\Users\Administrator\Desktop\blog\src\App.tsx

import React from 'react';
import './App.css';
import axios from 'axios';
interface IPost {
  userId: number;
  id ? : number;
  title: string;
  body: string;
}
const defaultPosts: IPost[] = [];
const App: React.FC = () => {
  const [posts, setPosts]: [IPost[], (posts: IPost[]) => void] = React.useState(defaultPosts);
  const [error, setError]: [string, (error: string) => void] = React.useState('');
  React.useEffect(() => {
    axios
      .get < IPost[] > ('http://localhost:5000/posts', {
        headers: {
          'Content-Type': 'application/json'
        }
      })
      .then(response => {
        setPosts(response.data);
      })
      .catch(ex => {
        setError('An unexpected error has occured');
      })
  },[])
  const handleDeleteClick = (post: IPost) => {
    axios.delete(`http://localhost:5000/posts/${post.id}`)
    .then(() => {
      setPosts(posts.filter(p => p.id !== post.id));
    });
  };
  return (
    <div className='App'>
      <ul className='posts'>
        {
          posts.map((post, index)=>{
            return(
              <li key={post.id}>
                <h3>{post.title}</h3>
                <p>{post.body}</p>
                <button>Update</button>
                <button onClick={() => handleDeleteClick(post)}>Delete</button>
              </li>
            )
          })
        }
      </ul>
      {error && <p className='error'>{error}</p>}
    </div>
  )
}
export default App;

Last updated

Was this helpful?