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
From your code, I'm guessing user is an object instead of an array. You are initializing the user as an array even though it should be an object (assuming from the use of user word here, i.e singular). I made the following changes:-
user_name or mobile_number as needed to update the state.The below code should work
function ContactForm() {
const [user, setUser] = useState({});
const submitForm = () => {
console.log(user);
};
return (
<div>
<input
type="text"
placeholder="name"
onChange={(e) =>
setUser({...user, user_name: e.target.value });
}
value={user.user_name}
/>
<input
type="text"
placeholder="mobile"
onChange={(e) =>
setUser({...user, mobile_number: e.target.value })
}
value={user.mobile_number}
/>
<button onClick={submitForm}>Submit</button>
</div>
);
}
I think you need to change your setState on the mobile input. Right now you're spreading the user as an array when you want it to be an object. When you do [...user] inside of the parent array, you create a new array instead of an object. Also, you need to make sure to edit the last element of the array. So:
setUser([...user, {...user[user.length], mobile_number: e.target.value }])
The parentheses get the last element of that array, not sure if that's what you're looking for. Pretty sure you need some way to identify which object in the array you want to use when editing the mobile number.