I was wondering if anyone could explain how I can have 2 onSubmit events in React? I have a button for clicking a form on submission, and it has a thank you message popping up, but I'm trying to clear the localStorage at the same the form is submitted. I have tried this:
const handleSubmit = (e) => {
e.preventDefault();
alert(`Thank you for your order! ^_^ Please check your texts for updates!`);
toggle()
};
const clearCartStorage = () => {
localStorage.clear();
}
<Form onSubmit={handleSubmit && clearCartStorage()}>
These work separately, but when I have the && only the clearCartStorage function will run without the handleSubmit pop up.
CodePudding user response:
Make a new function which calls those other functions:
<Form onSubmit={(e) => {
handleSubmit(e);
clearCartStorage();
})>
CodePudding user response:
Careful, you are invoking clearCartStorage
when you create the Form component there.
<Form onSubmit={handleSubmit && clearCartStorage()}> ❌❌❌
It should take one function which can call multiple.
I would set it up like this. It's more common to keep the function definition out of the returned JSX.
const MyComponent = () => {
const handleSubmit = (e) => {
e.preventDefault();
clearCartStorage()
alertUser()
};
const clearCartStorage = () => {
localStorage.clear();
}
const alertUser = () => {
alert(`Thank you for your order! ^_^ Please check your texts for updates!`);
toggle()
}
return <Form onSubmit={handleSubmit}>
}