0

I am handling multiple submitting events in parent component when form component submitted, it won't be a problem for me if I handle only a few events but with multiple events like the code below. I feel it's not cleans and too much await update(data); be repeated. How can I refactor it code to clean more or is there any other solution?

 function ProfilePage() { const { update } = useProfile(); const fullNameHandler = async (data) => { try { await update(data); toastify('Fullname updated!'); } catch (err) { toastify(err); } }; const usernameHandler = async (data) => { try { await update(data); toastify('Username updated!'); } catch (err) { toastify(err); } }; const passwordHandler = async (data) => { try { await update(data); toastify('Password updated!'); } catch (err) { toastify(err); } }; const phonenumberHandler = async (data) => { try { await update(data); toastify('Phone number updated!'); } catch (err) { toastify(err); } }; const emailHandler = async (data) => { try { await update(data); toastify('Email updated!'); } catch (err) { toastify(err); } }; const formList = [ { component: <Fullname onSubmit={fullNameHandler} />, }, { component: <Username onSubmit={usernameHandler} />, }, { component: <Password onSubmit={passwordHandler} />, }, { component: <PhoneNumber onSubmit={phonenumberHandler} />, }, { component: <Email onSubmit={emailHandler} />, }, ]; return ( // ...etc... ) } 

1 Answer 1

1

All these functions do that same thing, so you can use a single function to handle all of your inputs. You can also replace the async/await and try/catch with then/catch. Something like this for example:

const handleSubmit = (data, inputName) => { update(data) .then(() => { toastify(`${inputName} updated!`); }) .catch(toastify) }; 

And then call the function with the inputName parameter:

<Fullname onSubmit={data => handleSubmit(data, "Fullname")} /> 

Depending on what you're returning, you can also refactor the form list like this:

const formList = [ { name: "Fullname", component: Fullname }, ... ]; 

And then map:

formList.map(({ name, component: Input }) => ( <Input onSubmit={data => handleSubmit(data, name)} /> )); 
Sign up to request clarification or add additional context in comments.

4 Comments

onSubmit={data => handleSubmit(data, "Fullname")} does it affect performance? Should we handleSubmit passed as a reference like onSubmit={handleSubmit} ?
@Epple It is a controversial issue. I've never had a performance problem doing this. But I'll let you do your own research on this subject.
Thanks a lot! I really need coffee right now!
Oh, I solved this by onSubmit={handleSubmit.bind(name)}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.