Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How do I grab the value of an object within a functional component in React and set it within useState?

I am building a blog with React and Material UI. I have a dedicated page where I can view my current posts. I have added a delete icon that when clicked should delete the post from the local JSON file. I have tried using useState to store the value of the post id, and then insert it into the fetch API endpoint. However, I am unable to select the respective post id. I am also unsure if I am using the fetch request the right way.

const [postId, setPostId] = useState();
const deletePost = () => {
    fetch(`http://localhost:8000/posts/${postId}`, {
        method: 'DELETE'
        })
    }    

    return (
        <> 

            {posts.map((post) => (
                <Container maxWidth="lg" sx={{ border: 1, borderRadius: 3, mb: 5, p: 5 }}>

                    <IconButton onClick={deletePost} setPostId={post.id}>
                        <DeleteIcon />
                    </IconButton>

                </Container>
            ))}
        </>
    );

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried using useState to store the value of the post id, and then insert it into the fetch API

You don’t actually need to store it in the state. Just pass it directly to the deletePost function.

const deletePost = (postId) => {
   ...
}

<IconButton onClick={() => deletePost(post.id)}>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading