Getting undefined when inputted data in multiple fields

Issue

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

I have certain input fields in a table, which has input text and date field and the user has liberty to change input data accordingly. Assume we want to change input text of certain record which works properly but, when changed the date the previous input text value gets undefined. Similarly it happens with other record, when changed input text date data gets undefined. This can be seen in console. Please refer to to the code below.

const [dataNew, setDataNew] = useState([]);

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

console.log("data new", dataNew);

Below is the grid where text and date values are reflected

return (
    <>
      <Grid
        GridConfig={gridConfigData}
        GridData={gridData}
        OnTextCallback={handleChange}
        DateCallBack={handleChange}
      />
    </>
  );

Here the date and text data is handled which I’m trying to assign it to an array. In the dataNew const, you can observe the undefined values for date and text. My intention is that values which are selected should be set maybe its date or text.

Any appropriate solution highly appreciated.

Please also refer to codesanbox link: https://codesandbox.io/s/elated-varahamihira-xpjtdb?file=/src/Table.js:530-563



Solution

This question is not yet answered, be the first one who answer using the comment. Later the confirmed answer will be published as the solution.

This Question and Answer are collected from stackoverflow and tested by JTuto community, 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?