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

121
Visualizações
how to update nested state array and then return the entire array react

I'm using React Hooks. This is my state:

const [ chats, setChats ] = useState()

And i have this array in my "chats" state:

[
    {
        "messages": [ //I refer this field
            {
            "message": "hi",
            "seen": false,
            "_id": "61658b533da2d51eace71b31",
            "user": {"user data"}
            }
        ],
        "users": ["some data"],
        "avatar": "data",
        "_id": "61634b62c1a7612f04296335",
        "type": "private"
        },
    {
      "messages": [],
      "users": ["some data"],
      "avatar": "data",
      "_id": "616355d7e124771d98426240",
      "type": "private"
    }
]

So i just need to update the "messages" field from the "0" element of that "chat" array with this newMessage object:

{
  "message": "another hi",
  "seen": false,
  "_id": "61658f551ccbac34a8d10130",
  "user": {"some user data"}
}

I have tried with the most popular answer but it only returns the "messages" field, and i need to return the entire array.

Code:

setChats([...chats[currentlyChatIndex].messages, newMessage])
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can map over the array, and if you are at the currentlyChatIndex you can append the messages field.

Example

const data = [
    {
      "messages": 
      [
          {
            "message": "hi",
            "seen": false,
            "_id": "61658b533da2d51eace71b31",
            "user": "user data"
          }
      ],
      "users": ["some data"],
      "avatar": "data",
      "_id": "61634b62c1a7612f04296335",
      "type": "private"
    },
    {
      "messages": [],
      "users": ["some data"],
      "avatar": "data",
      "_id": "616355d7e124771d98426240",
      "type": "private"
    }
]

const addMessage = (index, message) => {
  return data.map((el, i) => i === index ? {...el, messages: [...el.messages, message]} : el)
}

console.log(addMessage(0, {message: 'another hi'}))

Your case

setChats(chats => chats.map((chat, index) => index === currentlyChatIndex ? 
     { ...chat, messages: [...chat.messages, newMessage] } : chat))
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