Medium
How to Implement a React Comment System with Form Validation and Loading States
You're building a comment system where users can write, edit, and delete their comments. The system needs to prevent duplicate submissions and handle loading states. What's missing in this implementation?
1function CommentForm({ onSubmit, initialValue = '', isEditing = false }) {2 const [comment, setComment] = useState(initialValue);3 const [status, setStatus] = useState('idle');45 const handleSubmit = async (e) => {6 e.preventDefault();7 if (status === 'submitting') return;89 setStatus('submitting');10 try {11 // Missing implementation12 _______________1314 setComment('');15 setStatus('success');16 } catch (error) {17 setStatus('error');18 }19 };2021 return (22 <form onSubmit={handleSubmit}>23 <textarea24 value={comment}25 onChange={(e) => setComment(e.target.value)}26 disabled={status === 'submitting'}27 />28 <button29 type="submit"30 disabled={status === 'submitting' || !comment.trim()}31 >32 {isEditing ? 'Update' : 'Post'} Comment33 </button>34 {status === 'error' && (35 <p className="error">Failed to post comment. Please try again.</p>36 )}37 </form>38 );39}