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

147
Visualizações
Adding an array and an object to an array react hooks

I'm trying to add an array and an object to an array.

This is my constructor

const [dashboard, setDashboard] = useState({ loading: true, data: [], address: '' })

and this is how I wanted the data to end up

{
   loading: true,
   data: [{id: 0, name: 'A'}, {id: 1, name: 'B'}],
   address: 'xxx'
}

I can't seem to figure it out and was only able to manage to add the arrays but not the other objects like loading and address with something like this but this is not what I need and I'm just giving an example of what I tried doing:

the constructor of this one in the bottom is different from what I want to use, I used something like this

const [dashboard, setDashboard] = useState([])

setDashboard((prev) => {
   return [...prev, newData]
})
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

const [dashboard, setDashboard] = useState({ loading: true, data: [], address: '' })

The line above looks great, no problems there.

setDashboard((prev) => {
   return [...prev, newData]
})

Doing this will set your dashboard variable to be an array, and is definitely not what you said you wanted.

setDashboard((prev) => {
  return {
    ...prev,
    data: [...prev.data, ...newData] // <-- assuming new data is an array
  }
})

Depending on what newData looks like you may need to manually merge the data into your previous data object. For instance, if you want to ensure you have no duplicate values in the array, or you need to sort them.

about 4 years ago · Juan Pablo Isaza Relatório

0

If I understand your problem correctly you are trying to do something like this:

setDashbaord(prevDashboard => ({ ...prevDashboard, address: "xxx", data: [...prevDashboard.data, newData] }));

Is that what you are looking for?

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