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

184
Visualizações
setState with return in TYPESCRIPT

Oops, my friends, I have this "problem" when using setState, as setState is not asynchronous I can't use it the way I want. I set the value and when calling the function to send back the value returns with "delay". How do I resolve this?

  const [quantityProduct, setQuantityProduct] = useState<number>(0);

function addQuantity() {
    var soma = Number(quantityProduct) + 1;
    setQuantityProduct(soma);
    sendProduct()
}
  
function sendProduct() {
    console.log(quantityProduct)
}

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

0

The issue is that the following two lines are asynchronous. What you experience is the second line gets executed before completing the first one.

setQuantityProduct(soma);
sendProduct();

You meant to call sendProduct when the quantityProduct gets updated. You should be using useEffect hook with quantityProduct in the dependency array.

Try like below.

  const [quantityProduct, setQuantityProduct] = useState<number>(0);
  function addQuantity() {
    var soma = Number(quantityProduct) + 1;
    setQuantityProduct(soma);
  }

  function sendProduct() {
    console.log(quantityProduct);
  }

  useEffect(() => {
    sendProduct();
  }, [quantityProduct]);

2nd way: calling the API inside setState callback

  function addQuantity() {
    setQuantityProduct((prevQuantity) => {
      var newQuantity = Number(prevQuantity) + 1;
      sendProduct(newQuantity);
      return newQuantity;
    });
  }
about 4 years ago · Juan Pablo Isaza Relatório

0

"setState is not asynchronous"

This isn't true. The documentation is clear on this:

React may batch multiple setState() calls into a single update for performance. Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

You need to use the useEffect hook to watch for changes in state (passing in the state you want to watch in a dependency array), and then perform an operation based on that change.

const [quantityProduct, setQuantityProduct] = useState(0);

function addQuantity() {
  const soma = Number(quantityProduct) + 1;
  setQuantityProduct(soma);
}

function sendProduct() {
  console.log(quantityProduct);
}

useEffect(() => {
  sendProduct();
}, [quantityProduct]);

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