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

151
Visualizações
React setState in two Async functions, second overwrites first

I have an interesting problem here I will try to outline here. I have a state object in React state that is updated in two separate async functions in this way:

const [someState, setSomeState] = useState({})

const somefunction1 = async () => {
  const res1 = ///some api call
  setSomeState({...someState, res1: res1})
}

const somefunction2 = async () => {
  const res2 = ///some api call
  setSomeState({...someState, res2: res2})
}

await someFunction1();
await someFunction2();

console.log(someState); //{res2: res2}

Based on the above example, I am not sure why res1 is missing in this state object when they are called separately, the second call effectively overwrites the changes made from the first call. What I really need this to look like when its done is:

console.log(someState); //{res1: res1, res2: res2}

Is there a better way to write this scenario so I get the expected outcome? Since one somefunction2 is supposed to wait until somefunction1 is complete, I am not sure why it is overwriting it. Any help will be appreciated. Thank you.

about 4 years ago · Juan Pablo Isaza
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