The onSubmit callback paymentHandler is supposed to run as soon as the form is submitted, I didn't specify button type. but as soon as I click submit button, nothing happens until I click the submit button again. The button and form inputs are styled components. They work fine in other pages.
const callPaystack = () => {
fetch('https://api.paystack.co/transaction/initialize', {
method: 'POST',
headers: {
'Authorization': `Bearer ${import.meta.env.VITE_PAYSTACK_SECRET_KEY}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: buyerEmail,
amount: totalPrice * 100,
channels: ["card", "bank", "qr", "ussd"],
metadata: {
"cancel_action": "https://crown-storex.netlify.app",
}
}),
}).then((res) => res.json())
.then((data) => {
setPaymentResult(data);
console.log(paymentResult)
})
}
const paymentHandler = async (e) => {
e.preventDefault();
await callPaystack();
location.href = paymentResult.data.authorization_url;
}
<form onSubmit={paymentHandler}>
<FormInput
label="Email"
name="email"
type="email"
value={buyerEmail}
onChange={(e) => setBuyerData({ ...buyerData, buyerEmail: e.target.value })}
required
/>
<Button buttonType={buyerEmail ? "inverted" : "disabled"} >Pay Now With Paystack</Button>
</form>
This should be happening because you are updating the state which updates after paymenthandler is completed entirely.
You should return the value from paymenthandler and use to set location.href