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

114
Visualizações
pushing a object into array state , on printing array it prints values with old state. the state objects contains inputs from form fields

am having a problem understanding react state . i am pushing an object on click of a button taking multiple values from input fields into array . onClick of button should show the latest state but its showing the previous input values from the form. how could i resolve this issue .

let addToList = ()=>{

let data={};

data.component=returnCmpName(SelCom);

data.question=question;

switch(SelCom){

case 1 : case 2:

data.required=checked;

data.errorMessage=errorMessage;

break;

case 3 : case 4 : case 5: data.options=NewList.slice(); break;

case 6:

data.fileAllowed=fileAllowed;

data.fileLimit=fileLimit;

break;

case 7: break;

case 8: break;

default:break;

}

rendcompState(prevData=>[data,...prevData])

console.log(rendComp)

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

0

The code you posted is a bit vague,
but it seems like you are trying to log the state right after setting it.
Setting a state in React is an asynchronous action, meaning that it runs in the background while you're code block continues.

This essentially means that when you are trying to log it, the state has still not finished setting.

What you can do instead, is use React's built-in useEffect hook,
which can take an array of dependencies and run a callback function once any of those dependencies have changed in value.

Should look like this:

useEffect(() => {
   console.log(state);
}, [state]);

You simply add this hook in your function component,
and the console.log will only run once the state actually finished updating.

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