Home > other >  How to store values of multiple variable in a single state?
How to store values of multiple variable in a single state?

Time:09-01

I have created a form, where there are multiple input fields. I want to store the data of those multiple input fields in a single useState variable. Following is the code:

import React, { useState } from "react";
const Form = () => {
  const [data, setData] = useState({
    firstName: "",
    lastName: "",
    phone: "",
    zipCode: "",
    age: "",
    role: "",
    helping_role: "",
    note: "",
    preferred_pronouns: "",
    email: ""
  });
  const [phoneNumber, setPhoneNumber] = useState({
    phoneNumber1: "",
    phoneNumber2: "",
    phoneNumber3: ""
  });
  const options = [
  ...
  ];

  const roles = [
  ...
  ];
  const helpOptions = [
 ...
  ];

  const onClickSendButton = async () => {
    const values = [...data];
    values.push({ firstName: "", lastName: "" });
    const savedData = setData(savedData);
    
  };
  return (
    <>
      <Navbar />
      <div className="form-main-container">
        <div className="form-field">
          <label>Name*</label>
          <br />
          <input
            className="input-field"
            id="name-field"
            type="text"
            placeholder="First Name"
            required="true"
            name="firstName"
            value={data.firstName}
            onChange={(e) => setData(e.target.value)}
          />

          <input
            className="input-field"
            id="name-field"
            type="text"
            placeholder="Last Name"
            name="lastName"
            required="true"
            value={data.lastName}
            onChange={(e) => setData(e.target.value)}
          />
        </div>
      
        <div className="form-field">
          <label>Phone Number*</label>
            ....
            ....
          <div className="form-field">
            <label>Zip Code*</label>
            <br />
            <input
              className="input-field"
              type="number"
              placeholder="###"
              required="true"
              name="zipCode"
              value={data.zipCode}
              onChange={(e) => setData(e.target.value)}
            />
          </div>
          <hr />
           ...    ...
          <button onClick={onClickSendButton}>Send</button>
          </div>
        </div>
      </div>
    </>
  );
};
export default Form;

I have tried storing all the variables details in a single useState variable but haven't been able to do so. How do I save all these input fields in a single useState variable?

CodePudding user response:

Your existing state(data) gets overridden with a new value(e.target.value) which is not what is desired.

Solution: Change the input onChange to

onChange={e => setData(prev => ({...prev, [e.target.name]: e.target.value}))}

example:

<input
  className="input-field"
  id="name-field"
  type="text"
  placeholder="First Name"
  required="true"
  name="firstName"
  value={data.firstName}
  onChange={(e) => setData(prev => ({...prev, [e.target.name]: e.target.value}))}
/>

CodePudding user response:

It is not working because your initial state is an object, but you are overriding it with an array or a string when using setData. >ou need to copy the previous value and then override the properties that you need.

    //Get prev data, override properties
    setData((prevData) => ({...prevData, firstName: "", lastName: ""}));
 onChange={(e) => setData((prevData) => ({...prevData, firstName: e.target.value}))}

CodePudding user response:

Used spread operator (... variable of use state )

  • Related