Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to assign input text values into an array?

In a table, certain input text fields are displayed. Accordingly data could be inputted in it. My intention is to club all the input data into an array. Each record has its specific unique id, which we get in console while we input in text box. Based on this id, I want to club into an array data. I’ve tried with one logic but gives error. Please have a look at the code below

// Here newData is an array of records which I'm displaying in Grid
const [dataNew, setDataNew] = useState(newData);

const textChange = (data) => {
    const { id, value } = data;
    setDataNew((prevInfo) => {
      const dataIndex = +id[id.length - 1];
      return {
        ...prevInfo,
         
        // Here I'm getting error in the below code snippet in prevInfo
        dataHere: Object.assign([...prevInfo.newData], { [dataIndex]: value })
      };
    });
  };

console.log('NEW DATA', newData)

Please suggest me if any changes to be done. Any solution highly appreciated

Please refer codesandbox link –> https://codesandbox.io/s/elated-varahamihira-xpjtdb?file=/src/Table.js:149-197

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

dataNew is initially an array, but you are returning an object from the setDataNew callback.

Also id is a number itself in your sandbox, so the following would suffice:

const textChange = (data) => {
  const { id, value } = data;
  setDataNew((prevInfo) => {
    const dataIndex = id - 1;
    prevInfo[dataIndex] = value;
    return [...prevInfo];
  });
};
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading