I am new in ReactJS world, I want to update my useState hook which contains array of objects, but it is now updating the data according to my requirement please help me in this.
ContactForm.js
function ContactForm() {
const [user, setUser] = useState([]);
const submitForm = () => {
console.log(user);
};
return (
<div>
<input
type="text"
placeholder="name"
onChange={(e) =>
setUser((state) => [...state, { user_name: e.target.value }])
}
value={user.user_name}
/>
<input
type="text"
placeholder="mobile"
onChange={(e) =>
setUser([...user, [...user, { mobile_number: e.target.value }]])
}
value={user.mobile_number}
/>
<button onClick={submitForm}>Submit</button>
</div>
);
}
I am expecting something like
[{
user_name:"abc",
mobile_number:"123"
}]
should be store in my state, but I am getting some different output like below
0: {user_name: "a"}
1: {user_name: "as"}
2: {user_name: "asd"}
3: (4) [{…}, {…}, {…}, {…}]
4: (5) [{…}, {…}, {…}, Array(4), {…}]
5: (6) [{…}, {…}, {…}, Array(4), Array(5), {…}]
please help me out from this issue, and please tell me how objects in an array in useState worked Thanks in advance
(updated stack) I tried so many ways, that's why you may feel what I have written in code, especially in the
<input/>
tag