0

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

2
  • what is your need ? Commented Sep 18, 2022 at 17:27
  • I want to add input text values in an array, with its unique id as its index... which can be seen in console Commented Sep 18, 2022 at 17:36

1 Answer 1

0

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

Sign up to request clarification or add additional context in comments.

2 Comments

Perfect.... this is the expected answer... Thanks
Hello... can you please look into this stackoverflow.com/questions/73768945/… the issue is when input text is changed date data is undefined.... and it happens vice-versa

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.