Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
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]

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This is why you don't use array indexes for element keys if the array can ever change. :-) The purpose of the key is to tell React which elements it can reuse. If you use the index 1 (for instance) as the key for on element A, but then remove an element at index 0 or 1, the next time you use the index 1 as the key, it's on a different element (element B). Instead, use the post Id (I assume it's unique to the post):

return <Post postId={post._id} key={post._id} setRefresh={setRefresh} refresh={refresh} />
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!