From d85cbc02915f8a6ce70aba5f2945a1d9fa0397bc Mon Sep 17 00:00:00 2001 From: OudomMunint Date: Sat, 17 Aug 2024 16:53:19 +1000 Subject: [PATCH] Optimized form submission logic for testing and add test data for dev env --- src/components/Contact.js | 47 ++++++++++++++++++++------------------- 1 file changed, 24 insertions(+), 23 deletions(-) diff --git a/src/components/Contact.js b/src/components/Contact.js index e96b4cf..06f9372 100644 --- a/src/components/Contact.js +++ b/src/components/Contact.js @@ -1,12 +1,11 @@ -import React, { useState } from "react"; +import React, { useState, useEffect, useCallback } from "react"; function ContactForm() { const isDevelopment = process.env.NODE_ENV === "development"; const [name, setName] = useState(""); const [email, setEmail] = useState(""); const [message, setMessage] = useState(""); - - const handleSubmit = async (event) => { + const handleSubmit = useCallback(async (event) => { event.preventDefault(); let data = { name, email, message }; try { @@ -14,31 +13,33 @@ function ContactForm() { setName(''); setEmail(''); setMessage(''); - data = { name: "testUser1", email: "test@test.com", message: "Hello, this is a test message." }; - console.log('Form submission successful:'); - console.log(data); + if (isDevelopment) { + data = { + name: "testUser1", + email: "test@test.com", + message: "Hello, this is a test message." + }; + } + console.log('Form submission successful:', data); } catch (error) { console.error('Form submission error:', error); console.log('Error caught'); } - }; + }, [name, email, message, isDevelopment]); - if (isDevelopment) { - try { - document.getElementsByClassName("submit").addEventListener("click", handleSubmit); - } - catch (error) { - console.error('Error:', error); - } - } - else { - try { - document.getElementsByClassName("submit").removeEventListener("click", handleSubmit); - } - catch (error) { - console.error('Error:', error); + useEffect(() => { + if (isDevelopment) { + const button = document.querySelector(".submit"); + if (button) { + button.addEventListener("click", handleSubmit); + } + return () => { + if (button) { + button.removeEventListener("click", handleSubmit); + } + }; } - } + }, [isDevelopment, handleSubmit]); return ( <> @@ -84,7 +85,7 @@ function ContactForm() {
{/* Submit */} -