1

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 };
1
  • Now I know my question is rubbish. Commented Feb 11, 2023 at 11:19

1 Answer 1

1

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}/>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.