Reputation: 229
I am trying to fetch both the input value save it in the state but it does take only last the Input field value.
When in useEffect console.log(state)
the object only stores and displays the last values lname
I am not able to get why its not storing fname
.
I want to store both the the value as object from input field.
const handleChange = idx => e => {
const { name, value } = e.target;
const rows = [...state.rows];
rows[idx] = {
...rows[idx]
[name]: value
};
setState({
rows
});
};
Upvotes: 1
Views: 306
Reputation: 53874
The problem is with handleChange
, you overriding the changed state:
const handleChange = (idx) => (e) => {
const { name, value } = e.target;
const rows = [...state.rows];
// Add ...rows[idx] to keep the values updated from other names
rows[idx] = { ...rows[idx], [name]: value };
setState({ rows });
};
Upvotes: 2
Reputation: 2877
you need to use ...rows[idx]
in your handleChange
const handleChange = idx => e => {
const { name, value } = e.target;
const rows = [...state.rows];
rows[idx] = { ...rows[idx], [name]: value }; //here
setState({
rows
});
};
Upvotes: 2