Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

125
Visualizações
Add item to the beginning of sorted object array

I have a small app with the following structure Posts -> Post -> Comments -> Comment.

The Posts component makes a request for an array of sorted posts by date (DESC). Each posts has its comments (which come through another request).

The problem I am facing. When I add a new item in the beginning of the posts array in order to keep it ordered and display the newest one, the entire component tree updates -> Post Component -> Comments Component, therefore for all the currently existing posts on the page, there will be again a request to get their comments even though they already have them.

If I add it in the end of the array, this does not happen, but if I sort them using a useMemo hook or something, the behavior described starts again

Anyone has any idea how I can get over this?

Part of the code is like this

      {sortedPosts && sortedPosts.map((post, index) => (
          <PostWrapper
            ref={posts.length === index + 1 ? setLoader : null}
            key={`${post?.id}${index}`}
            post={post}
          />
        )
      )}
const PostWrapper = forwardRef(({post}, ref) => (
  <Grid
    ref={ref}
    container
    justifyContent="center"
    item
    spacing={1}
    mt={2}
    xs={8}
  >
    <Post
      post={post}
    />
  </Grid>
))
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Here's what I understood, and I'll try to answer this as per my understanding. You have an array/list of Posts, and each post has an array/list of comments. I am assuming it is nested and posts are embedded in the same "Posts" array.

When you update the Posts array, React re-renders/refreshes the page with the new changes. When you add an element at the start, all the elements are pushed one position to the right, triggering a refresh for each post. And, for the same reason, you don't see that when you append it at the last.

Two ways to avoid additional API Calls for existing Posts. Choose which one suits your use-case better:

  1. Create a separate Dictionary of {PostID: {Comments}} and remove it from the Posts Array. Add to this dictionary when a new post is pushed/added, and retrieve it when you want to show. This way, even if there's a refresh trigger from React, it just picks it up from the dictionary and does not make an API Call.
  2. Append at the last (i.e. sort in ASC Order), and render the posts like a Stack (LIFO). This does not trigger a refresh, and I recommend this.

// Approach 2
this.setState(state => ({
    posts: [...state.posts, newPost]
}));

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda