I am facing a issue which I am unable to solve. Whenever I am trying to add Coupon, it successfully returns the percentage from the database but as I have created a state which is holding the initial percentage which I have assigned by default 0. Whenever, I am clicking the button, it returns the value but the expected output comes after clicking the buttons second time. That means, the state is holding the initial value. Same goes for the later values as well. Whenever I give another value and click the button that state is holding the previous value and I have to click the button second time to assign the new value.
const [coupons, setCoupon] = useState({
code: '',
percentage: ''
});
const handleChange = e => {
setCoupon({
...coupons,
[e.target.name]: e.target.value
})
}
const handleSubmit = e => {
const data = {
code: code
}
redeemCoupon(token, data)
.then(response => {
setCoupon({
...coupons,
code: "",
percentage: response.data[0].percentage,
})
const discountAmount = getOrderTotal() * percentage;
console.log(discountAmount);
})
.catch(err => { console.log(err) })
}
Output:
0 Checkout.js:85 1228.39 Checkout.js:85 1228.39 Checkout.js:85 1719.746
I have tried to use multiple solutions. My Expected output would be like this:
1228.39 Checkout.js:85 1719.746 Checkout.js:85
Whenever I will click on the button, It will change the state value to the data returned from the server and do the rest of the thing. But in this case, it is working one step ahead.