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

351
Visualizações
Cannot update the state of an object within the state (react)

I have an object variable within the state of my react app. I initialize it with the structure that I want the object to have. Late I am trying to update that object using the setState function. My issue is, I can't get it to actually update anything within the state. The way my code currently looks is:

// the initial state
var initialState = {
  object: {
   foo: '',
   bar: 0,
   array: [<an array of objects>]
 }
};

// in componentDidMount
this.state = initialState;

// updating the object that is within the state (also in componentDidMount)
let object = {
  foo: 'Value',
  bar: 90,
  array: [<a populated array of objects>]
};
this.setState(prevState => ({
  ...prevState.object,
  ...object
}));
console.log(this.state.object); // returns the object defined in initial state

I am really not sure how to fix this issue. I have also been trying a few other methods (especially the ones outlined in this post: Updating an object with setState in React I have not tried every method outlined in that post but the ones I have been trying have not been working and I figure that this means it is a mistake that does not involve which method I am using. Any insight into this issue would be greatly appreciated. I tried to make this code as concise as possible but if you want to see the exact code I am using (which is pretty much just this but more) just ask.

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

0

React.setState is reserved queue so that never called at lust billow under line of this.setState().
So suitable logging point is this.

this.setState((prevState) => {
  console.log('logging state: ', prevState)

 return {
  ...prevState.object,
  ...object
  })
)}

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