[SOLVED] Getting undefined when adding input text values into array

Issue

This Content is from Stack Overflow. Question asked by Prakash Patil

In a React project, I’m displaying certain records in a table which also has input text boxes for changing the values when needed. To process those changed records it needs to be added into an array, but, getting undefined when changed the values. Although each record is associated with unique id, unable to add in new array. Please refer to the code below.

const textChange = (data) => {
    const { id, value } = data;

    setDataNew((prevInfo) => {

      // Here the records are getting undefined and not getting added into array
      const dataIndex = id - 1;
      prevInfo[dataIndex] = value;
      return [...prevInfo];
    });
  };

Any suggestions and solution highly appreciated.

Please refer to code sandbox link for better clarity –> https://codesandbox.io/s/elated-varahamihira-xpjtdb?file=/src/Table.js:757-959



Solution

If I understood it correctly here is what you need to do if you need all the records which got updated :

  const textChange = (data) => {
    const { id, value } = data;
    setDataNew((prevInfo) => {
      const newList = [...prevInfo];
      const index = newList.findIndex((datum) => datum.id === id);
      if (index !== -1) {
        newList[index] = { id, value };
      } else {
        newList.push({ id, value });
      }
      return [...newList];
    });
  };

Mistake in your code

You were getting undefined because you were calculating index like :

 const dataIndex = id - 1;

if the changed object id was 6708 , you were adding element at 6707th index. Hence all first 6706 element were showing up as undefined.
console

Link : working demo


This Question was asked in StackOverflow by Prakash Patil and Answered by programoholic It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?