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

97
Visualizações
Adding value to an array in useState but only at a particular index of the array

I have a piece of state which holds an array of comments.

Each comment has an array of replies.

How can I add a reply value to the replies array of a specific comment within the comments array?

Here is my current attempt:

      if (data) {

        const isLargeNumber = (comment) => comment.id === reply.commentId;

        const idx = comments.findIndex(isLargeNumber);

        setPost({
          ...post,
          comments: {
            ...comments[idx],
            replies: [data.replyToComment, ...post.comments[idx].replies]
          }
        })

        resetValues();
      }

idx holds the correct value I need but I do not think my implementation is correct here.

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

As post.comments is an array, you certainly need to create an array, not a plain object with { }. You are missing one level in your nested structure (the array of comments, versus the specific comment). You can use Object.assign to replace the entry at [idx]:

  const idx = post.comments.findIndex(isLargeNumber);

  setPost({
    ...post,
    comments: Object.assign([...post.comments], {
      [idx]: {
        ...post.comments[idx],
        replies: [data.replyToComment, ...post.comments[idx].replies]
      }
    })
  });
about 4 years ago · Juan Pablo Isaza Relatório

0

Adapting from this example:

    setPost({
        ...post,
        comments: [
            ...post.comments.slice(0, idx),
            {
                ...post.comments[idx],
                replies: [...post.comments[idx].replies, data.replyToComment]
            },
            ...post.comments.slice(idx + 1)
        ]
    });
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