Melissa Stewart
Melissa Stewart

Reputation: 3605

How can I store and update multiple values in React useState?

I've a series of user data elements which I'm collecting inside a React component using hooks.

const [mobile, setMobile] = useState('');
const [username, setUsername] = useState('');
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [confirmPassword, setConfirmPassword] = useState('');

Each of these are updated as follows.

<input type="text"
       className="form-control"
       id="mobile"
       placeholder="Enter a valid mobile number"
       onChange={event => {setMobile(event.target.value)}}/>

Is there a more succint way to do this using an object as the variable?

Upvotes: 44

Views: 97608

Answers (5)

Helly Patel
Helly Patel

Reputation: 21

You may refer this (usestate with single object):

const [formData, setFormData] = useState({
    mobile: '',
    username: '',
    email: '',
    password: '',
    confirmPassword: ''
  });

  const handleChange = (event) => {
    // Update the state object with the new value
    setFormData({...formData, [event.target.name]: event.target.value });
  };

Upvotes: 0

surbhi singh
surbhi singh

Reputation: 1

to store multiple state in usestate for radio button in antd

 const [allValues, setAllValues ]= useState({
        validate:'',
        required:'',
        labelAlign:'',
        labelFontWeight:''
    })
    const changeHandler = (e, name) => {             
        setAllValues({
          ...allValues,                                
        [name]: e.target.value,          
        });
      };
     <Form.Item
            label="Validation"
            rules={[
              {
                required: true,
              },
            ]}
          >
          <Radio.Group
            onChange={(e) => changeHandler(e, "validate")}
            value={allValues.validate}
            style={{ paddingLeft: "15%" }}
          >
            <Radio value="True">True</Radio>
            <Radio value="False">False</Radio>
          </Radio.Group>
          </Form.Item>

Upvotes: 0

confused_
confused_

Reputation: 1681

Set initial values

const initialValues = {                   // type all the fields you need
name: '',
email: '',
password: ''
};

UseState

const [values, setValues] = useState(initialValues);       // set initial state

Handling the changes

const handleChange = (e) => {                
  setValues({
    ...values,                                // spreading the unchanged values
    [e.target.name]: e.target.value,          // changing the state of *changed value*
  });
};

Making the Form

<form>
  <input type="email"
   id="xyz"
   name="email"                                     // using name, value, onChange for applying changes
   value={email}
   onChange={changeHandler}
   placeholder="Enter your email"
   />
   // other inputs
</form>

Upvotes: 7

Rijo Joy
Rijo Joy

Reputation: 385

The above answer could create issues in some cases, the following should be the right approach.

const [allValues, setAllValues] = useState({
   mobile: '',
   username: '',
   email: '',
   password: '',
   confirmPassword: ''
});
const changeHandler = e => {
   setAllValues( prevValues => {
   return { ...prevValues,[e.target.name]: e.target.value}
}
}

Upvotes: 26

Shotiko Topchishvili
Shotiko Topchishvili

Reputation: 2943

You should add name attributes to input tags. Each name must refer to key in AllValues object.

const [allValues, setAllValues] = useState({
   mobile: '',
   username: '',
   email: '',
   password: '',
   confirmPassword: ''
});
const changeHandler = e => {
   setAllValues({...allValues, [e.target.name]: e.target.value})
}
return (
   <input type="text"
       className="form-control"
       id="mobile"
       name="mobile"
       placeholder="Enter a valid mobile number"
       onChange={changeHandler}
   />
   // ...
)

Upvotes: 91

Related Questions