Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is exactly to handle event in react component?

I am creating a component to promote reusability. In this component, I am handling the post submitting event when submitting form and I want to show status like success/error message if this post submitting was succeed/failed.

I am thinking of two ways to handle the onAddPost submitting event and show the status success/error:

1. Handle directly at the AddPost component:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

./components/add-post.js (children component):

function AddPost ({ onAddPost }) {
   
   const submitHandler = async (data) => {
     try {
       await onAddPost(data); 
       toastify('Add post successfully!'); // show success message 
     }
     catch (err) {
       toastify(err); // show error message
     } 
   }

   return (
     <form onSubmit={submitHandler}>
      ...
     </form>
   )
}

./pages/add-post.js (parent component):

...
const { addPost } = usePost();
<AddPost onAddPost={addPost}/>

2. Handle directly at the parent component (otherwise known as pages component or container component):

./components/add-post.js (children component):

function AddPost ({ onAddPost }) {
   
   const submitHandler = async (data) => {      
       onAddPost(data);          
   }

   return (
     <form onSubmit={submitHandler}>
      ...
     </form>
   )
}

./pages/add-post.js (parent component):

...
const { addPost } = usePost();

const addPostHandler = async (data) => {
     try {
       await addPost (data); 
       toastify('Add post successfully!'); // show success message 
     }
     catch (err) {
       toastify(err); // show error message
     }       
}

<AddPost onAddPost={addPostHandler}/>

I’m not sure what is the best way to improve my case to promote reusability AddPost component by two ways above?

>Solution :

Both of them are ok but I think second one is better, because there might be a case that you want add a post in AddPost component but don’t want to show toast (redirect to another page or etc) so in second pattern you wont faced any challenge. and it also obey Single-responsibility principle, it means that AddPost component just needs to have a form and call function addPost (not handing errors or etc)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading