I created five inputs and I am trying to get their values in an object after click
on the button. The problem I am facing is that after the button click I am getting only index
and value
of last updated input.
function App() {
const [dataItem, setDataItem] = useState({});
let arr = [1, 2, 3, 4, 5];
function getMultipleInputValue(index, e) {
let newObj = {}
newObj[index] = e.target.value;
setDataItem(newObj)
}
function getDtat() {
console.log("dataItem", dataItem)
}
return (
<>
{arr.map((data, index) => {
return (
<input type='text' name={index} key={data} onChange={(e) =>
getMultipleInputValue(index, e)} />
)
})}
<button onClick={() => getDtat()}>Click here</button>
</>
);
}
export default App;
2
Answers
You have to use all the previous values of the current state, and update the new value, something like this:
The problem is that you’re resetting the state with a new object:
Instead, what you need to do is update the current state object:
Please check the fixed demo.
See also React docs on how to update the state based on the previous state.