From 86bb20377b2d7fa6bdc7ae2f7bc2e67f1053eeda Mon Sep 17 00:00:00 2001 From: Hamzah Khan <66473175+hamzahshahbazkhan@users.noreply.github.com> Date: Wed, 9 Oct 2024 02:29:40 +0530 Subject: [PATCH] Added checks so that comments are not blank. (#1441) * added checks for blank comments * added checks for blank comments --- src/components/comment/CommentInputForm.tsx | 33 ++++++++++++++++----- tsconfig.json | 2 +- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/src/components/comment/CommentInputForm.tsx b/src/components/comment/CommentInputForm.tsx index 039209d7c..be991647e 100644 --- a/src/components/comment/CommentInputForm.tsx +++ b/src/components/comment/CommentInputForm.tsx @@ -1,5 +1,5 @@ 'use client'; -import React, { useEffect } from 'react'; +import React, { useEffect, useState } from 'react'; import { Button } from '../ui/button'; import { useAction } from '@/hooks/useAction'; import { createMessage } from '@/actions/comment'; @@ -15,6 +15,8 @@ const CommentInputForm = ({ parentId?: number | undefined; }) => { const currentPath = usePathname(); + const [isButtonDisabled, setButtonDisabled] = useState(true); + const [commentText, setCommentText] = useState(''); const formRef = React.useRef(null); const textareaRef = React.useRef(null); const { execute, isLoading, fieldErrors } = useAction(createMessage, { @@ -29,7 +31,6 @@ const CommentInputForm = ({ const handleFormSubmit = (e: React.FormEvent) => { e.preventDefault(); const formData = new FormData(e.target as HTMLFormElement); - const content = formData.get('content') as string; execute({ @@ -38,7 +39,14 @@ const CommentInputForm = ({ parentId, currentPath, }); + setCommentText(''); }; + + const isAllSpaces = (str: string): boolean => /^\s*$/.test(str); + + const isCommentValid = () => { + return !isAllSpaces(commentText); + } // Function to adjust the height of the textarea const adjustTextareaHeight = () => { @@ -48,6 +56,14 @@ const CommentInputForm = ({ } }; + useEffect(() => { + if (!isCommentValid() || isLoading) { + setButtonDisabled(true) + } else { + setButtonDisabled(false) + } + }, [commentText]) + // Effect to handle the initial and dynamic height adjustment useEffect(() => { const handleKeyDown = (event: KeyboardEvent) => { @@ -78,9 +94,6 @@ const CommentInputForm = ({ }; }, []); - const handleTextChange = () => { - adjustTextareaHeight(); - }; return (
{ + adjustTextareaHeight(); + setCommentText(e.target.value); + }} // Adjust height on text change /> - + ); }; diff --git a/tsconfig.json b/tsconfig.json index 88f05644b..3c4144d07 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -26,4 +26,4 @@ }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"] -} +} \ No newline at end of file