Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda