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:
./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?
CodePudding user response:
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)