Xây dựng editPost method setEditPost (P2)
PreviousXây dựng editPost method setEditPost (P1)NextXây dựng thêm post phương thức post trong axios (ok)
Last updated
Was this helpful?
Last updated
Was this helpful?
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('');
const [editPost, setEditPost]: [IPost, (post: IPost) => void] = React.useState({ body: '', title: '', userId: 1 });
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));
});
};
const handleUpdateClick = (post: IPost) => {
setEditPost(post);
};
const handleTitleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setEditPost({ ...editPost, title: e.currentTarget.value });
};
const handleBodyChange = (e: React.ChangeEvent<HTMLTextAreaElement>) => {
setEditPost({ ...editPost, body: e.currentTarget.value });
};
const handleSaveClick = () => {
if (editPost.id) {
axios
.put<IPost>(`http://localhost:5000/posts/${editPost.id}`,editPost,{
headers: {
'Content-Type': 'application/json'
}
})
.then(()=>{
setEditPost({
body: '',
title: '',
userId: 1
});
setPosts(posts.filter(post => post.id !== editPost.id).concat(editPost));
})
.catch(error => {
setError('An unexpected error has occured');
})
}
}
return (
<div className='App'>
<div className='post-edit'>
<input type='textarea' placeholder='Enter title' value={editPost.title} onChange={handleTitleChange}/>
<textarea placeholder='Enter body' value={editPost.body} onChange={handleBodyChange}/>
<button onClick={handleSaveClick}>Save</button>
</div>
<ul className='posts'>
{
posts.map((post, index)=>{
return(
<li key={post.id}>
<h3>{post.title}</h3>
<p>{post.body}</p>
<button onClick={() => handleUpdateClick(post)}>Update</button>
<button onClick={() => handleDeleteClick(post)}>Delete</button>
</li>
)
})
}
</ul>
{error && <p className='error'>{error}</p>}
</div>
)
}
export default App;