Skip to content

Commit

Permalink
Feat: Enhance Error Handling on 'ContactForm' component
Browse files Browse the repository at this point in the history
- Move Form-element reset method within successful try-block.
- Create function to handle the submitButton error content.
- Add error handling for 'fetch' request.
  • Loading branch information
ITurres committed Sep 25, 2023
1 parent 1dc15bf commit 4ae178b
Showing 1 changed file with 17 additions and 4 deletions.
21 changes: 17 additions & 4 deletions src/components/UI/ContactForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,15 @@ const ContactForm: React.FC = () => {
[],
);

const submitButtonErrorContent = (error: Error | string) => {
if ($submitButton.current) {
$submitButton.current.textContent = '';
$submitButton.current.appendChild(
document.createTextNode(`Error! ${error}`),
);
}
};

const submitForm = async () => {
try {
await fetch(actionURL, {
Expand All @@ -44,9 +53,14 @@ const ContactForm: React.FC = () => {
Accept: 'application/json',
},
});
} catch (error) {
console.error(error);
// TODO: Add error handling

$form.current?.reset();
} catch (error: Error | unknown) {
if (error instanceof Error) {
submitButtonErrorContent(error);
} else {
submitButtonErrorContent(String(error));
}
}
};

Expand All @@ -57,7 +71,6 @@ const ContactForm: React.FC = () => {

if (allValidInputs) {
submitForm();
$form.current?.reset();
}
};

Expand Down

0 comments on commit 4ae178b

Please sign in to comment.