skip to Main Content

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


  1. You have to use all the previous values of the current state, and update the new value, something like this:

    setDataItem(prevState => Object.assign({}, prevState, newObj));
    
    Login or Signup to reply.
  2. The problem is that you’re resetting the state with a new object:

      function getMultipleInputValue(index, e) {
        let newObj = {}
        newObj[index] = e.target.value;
        setDataItem(newObj) // resets the state to a new object
      }
    

    Instead, what you need to do is update the current state object:

      function getMultipleInputValue(index, e) {
        setDataItem(newObj => ({...newObj, [index]: e.target.value}))
      }
    

    Please check the fixed demo.

    See also React docs on how to update the state based on the previous state.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search