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>
</ >
);
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