Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way of handling form data via React useState()?

Just wondering if anyone has a better solution to stop repetitiveness in my code? I currently am using useState() to handle user data and it's fairly repetitive as there are loads of different fields. Here is my code below:

const [lname, setLast] = useState<string>("");
const [country, setCountry] = useState<string>("");
const [phone, setPhone] = useState<string>("");
const [email, setUsername] = useState<string>("");
const [username, setEmail] = useState<string>("");
const [password, setPassword] = useState<string>("");
const [cpassword, setCPassword] = useState<string>("");

The Form itself (summarized):

<IonItem>
    <IonLabel position={"stacked"}>First Name</IonLabel>
    <IonInput type={"text"} value={fname} placeholder="Enter Your First Name" onIonChange={(event) => setFirst(event.detail.value ?? '')}/>
</IonItem>

I saw before in another post you could use an interface, but I am unsure how I could implement it with the useState() or if it would be the best approach for my code as I am then passing the data to an Axios POST request to the backend to be processed

    const handleRegistration = async () => {
        await axios.post('http://localhost:3000/register', {
            fname: fname,
            lname: lname,
            country: country,
            phone: phone,
            email: email,
            username: username,
            password: password,
            cpassword: cpassword
        }).then(res => {
            console.log(res);
            onRegister();
        }).catch(err => {
            console.log(err);
        });
    }
like image 307
IAmAndy Avatar asked Mar 02 '23 16:03

IAmAndy


1 Answers

You can handle control data in a single useState :

import React, { useState } from "react";

const initialValues = {
        fname: "",
        lname: "",
        country: "",
        phone: "",
        email: "",
        username: "",
        password: "",
        cpassword: ""
};

export default function Form() {
  const [values, setValues] = useState(initialValues);

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    setValues({
      ...values,
      [name]: value,
    });
  };

  return (
        <form>
          <input
            value={values.fname}
            onChange={handleInputChange}
            name="fname"
            label="fname"
          />
          <input
            value={values.lname}
            onChange={handleInputChange}
            name="lname"
            label="lname"
          />
           // ... Rest of the input fields
          <button type="submit"> Submit </button>
        </form>
  );
}

Also, when sending the payload:

const handleRegistration = async () => {
        await axios.post('http://localhost:3000/register', {
            fname: values.fname,
            lname: values.lname,
            //Rest of the input fields
        }).then(res => {
            console.log(res);
            onRegister();
        }).catch(err => {
            console.log(err);
        });
    }
like image 131
neeraj tk Avatar answered Mar 05 '23 15:03

neeraj tk