Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

useState to update multiple values in React

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?

like image 880
Melissa Stewart Avatar asked Jan 19 '20 20:01

Melissa Stewart


People also ask

Can I use multiple useState in React?

Yes. In fact that's how it was designed to be used. You just can't conditionalize the calls to useState because the call order matters to React. The number of times you called useState is tracked and React expects the same amount of calls each time.

How do you update an array in useState?

myArray. push(1); However, with React, we need to use the method returned from useState to update the array. We simply, use the update method (In our example it's setMyArray() ) to update the state with a new array that's created by combining the old array with the new element using JavaScript' Spread operator.


2 Answers

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}
   />
   // ...
)
like image 118
Shotiko Topchishvili Avatar answered Oct 11 '22 14:10

Shotiko Topchishvili


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}
}
}
like image 40
Rijo Joy Avatar answered Oct 11 '22 12:10

Rijo Joy