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>
))}
</>
);
CodePudding user response:
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)}>