I'm learning React through this tutorial on Youtube.
I've looked through many answers but I can't find a similar case. I don't think I'm mutating data since the filter method in BlogList.jsx does return a filtered array, and I'm passing that newly created array to setState. (in this case, setBlogs
)
Home.jsx
import { useState } from "react";
import BlogList from './BlogList';
import { blogData } from '../data';
function Home() {
const [blogs, setBlogs] = useState(blogData);
function handleDelete(id) {
const newBlogs = blogs.filter((blog) => blog.id !== id);
setBlogs(newBlogs);
console.log(blogs);
console.log(newBlogs);
}
return (
<div className="home">
<BlogList blogs={blogData} handleDelete={handleDelete}/>
</div>
);
}
export default Home;
BlogList.jsx
function BlogList({ blogs, handleDelete }) {
return (
<div className="blog-list">
{blogs.map((blog) => (
<div className="blog-preview" key={blog.id}>
<h2>{blog.title}</h2>
<p>Written by {blog.author}</p>
<button onClick={() => handleDelete(blog.id)}>Delete</button>
</div>
))}
</div>
);
}
export default BlogList;
data.js
import { v4 as uuidv4 } from 'uuid';
// blog initial data.
const blogData = [
{
title: "Master HTML",
body: "lorem ipsum...",
author: "umaru-chan",
id: uuidv4(),
},
{
title: "CSS Is Hard!",
body: "lorem ipsum...",
author: "ebina-chan",
id: uuidv4(),
},
{
title: "JavaScript makes no sense",
body: "lorem ipsum...",
author: "kubo-san",
id: uuidv4(),
},
];
export { blogData };
in home.jsx you pass blogData to BlogList while setBlogs change blogs state not blogData
<BlogList blogs={blogData} handleDelete={handleDelete}/>
change to :
<BlogList blogs={blogs} handleDelete={handleDelete}/>