Skip to content

Commit

Permalink
add empty input check before attempting to submit it
Browse files Browse the repository at this point in the history
  • Loading branch information
ob6160 committed Oct 3, 2024
1 parent 167573b commit 4a92dcd
Showing 1 changed file with 37 additions and 29 deletions.
66 changes: 37 additions & 29 deletions src/components/Feedback/Feedback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ enum FeedbackState {
SUCCESS = 0,
FAILURE = 1,
PENDING = 2,
INVALID_INPUT = 3,
}

const Feedback = () => {
Expand All @@ -19,47 +20,53 @@ const Feedback = () => {
const emailInput = useRef<HTMLInputElement>();

const submitFeedback = async () => {
setSubmitState(FeedbackState.PENDING);
const hasUserInputText = feedbackTextArea.current?.value.length > 0;

if (!hasUserInputText) {
setSubmitState(FeedbackState.INVALID_INPUT);
return;
}

// Only attempt submit if the user has typed something in the text area
const hasUserInputText = feedbackTextArea.current?.value.length > 0;
setSubmitState(FeedbackState.PENDING);

if (hasUserInputText) {
const input = feedbackTextArea.current.value;
const payload = {
text: input,
email: emailInput.current.value,
route: window.location.pathname,
};

try {
await fetch('/api/feedback', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});

// eslint-disable-next-line functional/immutable-data
feedbackTextArea.current.value = '';
// eslint-disable-next-line functional/immutable-data
emailInput.current.value = '';

setSubmitState(FeedbackState.SUCCESS);
} catch (e) {
setSubmitState(FeedbackState.FAILURE);
}
const input = feedbackTextArea.current.value;
const payload = {
text: input,
email: emailInput.current.value,
route: window.location.pathname,
};

try {
await fetch('/api/feedback', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(payload),
});

// eslint-disable-next-line functional/immutable-data
feedbackTextArea.current.value = '';
// eslint-disable-next-line functional/immutable-data
emailInput.current.value = '';

setSubmitState(FeedbackState.SUCCESS);
} catch (e) {
setSubmitState(FeedbackState.FAILURE);
}
};

return (
<Stack spacing="1rem" padding="0.5rem" width="fit-content">
{submitState === FeedbackState.SUCCESS && <Badge>Thank you!</Badge>}

{submitState === FeedbackState.INVALID_INPUT && (
<Badge>Please enter some feedback</Badge>
)}
<label htmlFor="emailInput" style={{ fontWeight: 'bold' }}>
Email (optional)
</label>

<InputField
id="emailInput"
ref={emailInput}
Expand All @@ -70,6 +77,7 @@ const Feedback = () => {
<label htmlFor="feedbackTextArea" style={{ fontWeight: 'bold' }}>
Feedback
</label>

<TextArea
ref={feedbackTextArea}
id="feedbackTextArea"
Expand Down

0 comments on commit 4a92dcd

Please sign in to comment.