I'm having maybe what seems to be a basic trouble, but I just couldn't find solution to this problem. I'm passing handleSubmit function, which is asynchronous, but it doesn't return any value, from a parent to a child form component. After It's called in a child component I want to clear inputs as well as close the modal. In my case, input values are cleared and modal is closed before handleSubmit has finished executing. I'm using React with TypeScript in this project. If anyone could help I would be grateful. Thanks in advance
const createVariation = (variationType: string, variationValues: string[]): void => {
setLoading(true);
setTimeout(() => {
storeProductVariant(product.id, variationType, variationValues, accessToken)
.then(() => {
showProductVariants(product.id, accessToken)
.then((response) => {
dispatch(actionsProducts.showProductVariants(response.data.data));
});
showProductSkus(product.id, accessToken)
.then((response) => {
dispatch(actionsProducts.showProductSkus(response.data.data));
});
setLoading(false);
})
.catch((error) => {
setError(error.response.data.errors.variant[0]);
setLoading(false);
setTimeout(() => {
setError('');
}, 3000);
});
}, 1000);
};
const onSubmit = (event: React.FormEvent<HTMLFormElement>): void => {
event.preventDefault();
if (validateInputs(
inputValues.variationType,
inputValues.variationValues,
)) {
handleSubmit(inputValues.variationType, inputValues.variationValues, variantId);
Problem is here since I can't call .then() because function is void
setInputValues({
variationType: '',
variationValues: [],
variation: '',
});
handleClose();
setSelectedVariations([]);
}
};
What you need could be a little complex, however you may achieve this by the following steps:
Keep a state variable in parent component e.g. submissionDone like loading. And pass this to your child component.
Update submissionDone to true when the promise is resolved in parent.
The changed/updated value of submissionDone will be reflected in the child component.
Clear your inputs or anything else in the child component based on this variable.
Since you have not provided full code, I am giving a hint that - this logic in child component can be written inside a useEffect if you are using functional component or componentDidUpdate if you are using class components.