'On removing 1 element from array, map function removes only last element in react

I'm taking an array of posts from the backend and map through that array to display posts. But when I'm removing any one element and setting it again to useState, it just renders all elements except the last one. But when I refresh the page it shows the actual array that should be rendered without refreshing the page.

function Feed() {

   const [posts, setPosts] = React.useState(null);
   const [error, setError] = React.useState(false);
   const [isLoading, setIsLoading] = React.useState(true);
   const [refresh, setRefresh] = React.useState(false);

   const {user} = isAuthenticated();

   const loadPosts = () => {
          setIsLoading(true);
          getPosts()
          .then(data => {
                 if(data.error)
                        setError(error)
                 else {
                        console.log(data);
                        setPosts(data);
                        setIsLoading(false);
                 }
          })
          .catch(err => console.log(err))
   }

   React.useEffect(() => {
          loadPosts();
          console.log(posts); //here it logs actual posts array with the right element removed but it doesn't render the same array 
   }, [refresh]);

   React.useEffect(() => {
          loadPosts();
   }, []);

   return (
          <div>
                 <Header />
                        <div className="container">
                               <div className="row">
                                      <div className="col-8 mx-auto">
                                             
                                             <div><Link to={`/user/${user._id}/post/create`}><button className="btn btn-purple rounded-3 col-12 p-3 mx-auto mt-4 mb-5 fw-bold" type="submit"><i class="fas fa-plus"></i><strong>  New Post</strong></button></Link></div>

                                             {posts && (posts.map((post, index) => {
                                                    return <Post postId={post._id} key={index} setRefresh={setRefresh} refresh={refresh} />
                                             }))}

                                      </div>
                               </div>
                        </div>
                 <Footer />
          </div>
   );
}

export default Feed;

The array is updating, when one element is removed but in rendering, it just removes last element, not deleted one.

[1]: https://i.stack.imgur.com/6x9eS.png [Before deleting 1 element][1]

[1]: https://i.stack.imgur.com/zPUnb.png [after deleting first element, it removes the last one in rendering only. In array, it removed the first one.][1]



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source