iamshaunjp / iamshaunjp/Complete-React-Tutorial
Proper way to update state in Home when deleting a blog record in BlogList component?
- Dominant language
- No language data
- Stars
- 2k
- Forks
- 1.8k
- PR merge metrics
- No merged PRs in 30d
Description
Hi Shaun,
THANKS for incredible videos!
I have a small question concerning state update, when we delete a blog record directly from `Home` in `BlogList` component, not in `BlogDetails`.
In Lesson 13 we've used the callback function to handle delete:
```jsx
import { useState } from "react";
import BlogList from "./BlogList";
const Home = () => {
const [blogs, setBlogs] = useState([
{ title: 'My new website', body: 'lorem ipsum...', author: 'mario', id: 1 },
{ title: 'Welcome party!', body: 'lorem ipsum...', author: 'yoshi', id: 2 },
{ title: 'Web dev top tips', body: 'lorem ipsum...', author: 'mario', id: 3 }
])
const handleDelete = (id) => {
const newBlogs = blogs.filter(blog => blog.id !== id);
setBlogs(newBlogs);
}
return (
);
}
export default Home;
```
```jsx
const BlogList = ({ blogs, title, handleDelete }) => {
return (
{ title }
{blogs.map(blog => (
{ blog.title }
Written by { blog.author }
handleDelete(blog.id)}>delete blog
))}
);
}
export default BlogList;
```
Then in Lesson 31 we've moved all logic to `useFetch` hook, so state is updated for `BlogDetails` page:
```jsx
import { useHistory, useParams } from "react-router-dom";
import useFetch from "./useFetch";
const BlogDetails = () => {
const { id } = useParams();
const { data: blog, error, isPending } = useFetch('http://localhost:8000/blogs/' + id);
const history = useHistory();
const handleClick = () => {
fetch('http://localhost:8000/blogs/' + blog.id, {
method: 'DELETE'
}).then(() => {
history.push('/');
})
}
return (
{ isPending &&
{ error &&
{ blog && (
{ blog.title }
Written by { blog.author }
delete
)}
);
}
export default BlogDetails;
```
And what if I want to add delete button directly to the `BlogList` component to delete a blog record from Home page?
What is the easiest or the best approach to achieve something like this?
Notice `handleDeleteClick` is in `BlogList` not in `BlogDetails`.
```jsx
import { Link } from "react-router-dom";
const BlogList = ({blogs, title}) => {
const handleDeleteClick = (id) => {
fetch(`http://localhost:8000/blogs/${id}`, {
method: 'DELETE'
});
}
return (
{title}
{blogs.map((blog) => (
{blog.title}
Written by {blog.author}
handleDeleteClick(blog.id) }>delete
))}
);
}
export default BlogList;
```
```jsx
import './BlogList'
import BlogList from "./BlogList";
import useFetch from "./hooks/useFetch";
const Home = () => {
const {data: blogs, isPending, error} = useFetch('http://localhost:8000/blogs');
return (
{ error &&
{isPending &&
{blogs && }
);
}
export default Home;
```
Thanks!
Contributor guide
No contributing guide indexed for this repository
Assessment
This issue has not been assessed yet.