I have a button with an onclick event
. This button closes a dialog and changes its value.
I have two functions, one that changes the buttons value handleChange
and the other that closes the dialog and displays an alert to confirm onSubmit
.
Problem:
I tried calling the two functions separetly on the onClick event
. While doing this the function handleChange
works and the onSubmit
does not.
onClick={() => {
handleChange();
onSubmit();
}}
So I tried calling the handleChange
function inside the onSubmit
function.
const onSubmit = ()=> {
reset();
toast("Default Notification !");
handleChange();
};
onClick={() => {
onSubmit();
}}
Where I think it's the problem:
My onSubmit
function has an alert made of this library https://fkhadra.github.io/react-toastify/introduction/ and can not be changed for another library or a simple alert();
BUT if I try with an alert();
the two functions are displayed but I want the handleChange();
to run first and then the other.
For this I tried calling my onSubmit
function inside handleChange();
but it does not work. Also tried changing the order of calling the functions in the onclick
event but it doesn't work either
Edit
My on submit function :
const onSubmit = ()=> {
reset();
alert("Default Notification !");
handleChange();
};
My handleChange function:
const handleChange = () => {
setChange((prevState) => (prevState === 2 ? 0 : prevState + 1));
};
My onclick event:
<Button
variant="contained"
onClick={() => {
// handleChange();
onSubmit();
}}
>
Wrap the function or statement you want to execute after handleChange()
inside setTimeout
with 0 milliseconds. This will make sure the function or statement gets executed after all the synchronous tasks are finished executing (in this case handleChange()
).
const onSubmit = () => {
handleChange();
setTimeout(() => {
alert("Default notification"); // or any other function or statement you want to execute after handleChange().
}, 0);
};