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

106
Visualizações
Setting state not working after the first API call in react

I am sending a POST request to an endpoint in react using axios and if my returned response is successfull I am setting some state.

Here is my code:

axios.post('/some/endpoint', {mydata})
      .then(res => {
          console.log(res.data);
          if(res.data.success)
          {
            setMsg('successful');
            setActive('alert alert-success fade-out');      
          }
          else
          {
            setMsg('Oops! An error occured!');
            setActive('alert alert-danger');
          }
    })

After the first API request, everything is fine, I get the message and it fades out, Although If I try to send another request, It doesn't appear again and start to fade out, Why isn't the setMsg and setActive calls firing?

Heres the render:

    return (
      <>
        <Modal open={open} onClose={onCloseModal} center closeIcon={closeIcon} modalId="response-modal">
          <div className="qr-modal-header-stock">
            <h5>Enter fulfillment stock</h5>
            <p>{title}</p>
            <p>Fulfilment Center: {fulfilmentCenterName}</p>
            <p>Existing stock: {stock}</p>
            <p className={active} style={{opacity:0}}>{msg}</p>    <-- this appears firstly but not the second time when I submit the form, why?
            <form onSubmit={handleSubmit}>
                <input type="hidden" name="ean" value={data} />
                <input type="hidden" name="product_stock" value={newStock} />
                <input type="number" class="form-control" onChange={e => setNewStock(parseInt(e.target.value) + parseInt(stock))}/> <br />
                <input type="submit" class="btn btn-primary form-control" id="submit-fulfilment-center" value="Save"/>
            </form>
            <br />
            <p>New stock: {isNaN(newStock) ? 0 : newStock}</p>
            <button className="btn btn-primary" onClick={onCloseModal}>Scan another ean</button>
          </div>
        </Modal>
      </ >
    );

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

0

You should use "useState" hook and watch "Msg" and "Active" states for changes.

useState(()=>{
    // do somthing here 
},[Msg,Active])

using this will re-render the page every time the value of "Msg" or "Active" changes.

Notice : Do Not set states and watch them in the same useState hook , this will will cause an infinite rendring loop

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