I’m building the client page with Next.js. I have function handleSubmit that calls API to create a new product. It is called when the user clicks a button. In handleSubmit, I check if the response returns a 403 error, which means the access token has expired or is invalid, and if there is, I will call the refresh token API (updateTokens) and store the new access token along with the refresh token in local storage. I want to recursively call the handleSubmit function again after calling updateTokens. However, Typescript complains about the even parameter, saying Argument of type ‘FormEvent’ is not assignable to parameter of type ‘ChangeEvent’. And I also think the function will stuck in an infinite loop.
I think the idea to call the function again after reset access token and refresh token is the way to go, but I don’t know how to handle this case. It’s pretty simple if the API is called inside useEffect function, but this function is trickier because it is called upon clicking a button, not inside useEffect.
const handleSubmit = async (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
const productData = {
productName,
brand,
productDescription,
stockQuantity,
retailPrice,
COGS,
variants,
warehouse_enter_date,
exp_date,
imageURL,
};
try {
const response = await fetch(
"http://localhost:4000/dashboard/product/new",
{
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify(productData),
}
);
console.log(response);
if (!response.ok) {
if (response.status === 403) {
updateTokens(refreshToken); // this function will call refresh token API and store new API in local storage
handleImageUpload(event); // this is the recursive part, but typescript complains about the event parameter
} else {
throw new Error("Failed to get product details");
}
}
const responseData = await response.json();
console.log(responseData);
if (!responseData || !responseData.product || !responseData.product._id) {
throw new Error(
"No response data or no responseData.product or no responseData.product._id"
);
}
console.log("Product created successfully", responseData);
router.push(`/dashboard/product/${responseData.product._id}`);
} catch (error) {
if (error instanceof Error) {
console.error("Error creating product:", error.message);
} else {
console.error("Unknown error:", error);
}
}
};