I'm in the midst of making a facebook clone. One of the main components of this site, is a feed that contains a list of posts. These posts are coming from the databse and are being rendered dynamically which is all good.
in Feed.js
const [posts, setPosts] = useState([]);
...
<div id='feed' role="feed">
{posts.map(
post => ( <Post setPosts={ setPosts } post={ post } key={ post._id } /> )
)}
</div>
in Post.js
const handleClick = async () => {
try {
await fetch(`/posts/${post._id}`, {
method: 'delete',
headers: {
'Authorization': `Bearer ${token}`
}
})
} catch (err) {
console.error(err.message);
}
};
<div className="post">
<article data-cy="post" key={ post._id }>{ post.message }</article>
<button onClick={handleClick}>delete post</button>
</div>
Where Post is a child of Feed.
When the delete button is clicked, the post is deleted from the database as expected, however it is not removed from the page until the browser is refreshed.
How could I have so that when the delete button within the post component is clicked, that the feed component is also re-rendered? I have thought about handing state down, but in order for me to delete a specific post from an array would require me to hand down both posts
and setPosts
as props, is this bad practice? And what would best practice in React for this scenario, as I feel this is something I will come across a lot.