Home > Blockchain >  While updating data for one field shows undefined for other in an object
While updating data for one field shows undefined for other in an object

Time:10-14

In a Grid, certain records are populated, which also includes two input fields one for date and other for text. When changed data for date, text data gets undefined and when text is changed date is undefined which can be observed in console. After changing data I need to save it in the function. Please refer to the code below:

Following is the updateGrid function which I'm getting from Grid

<Grid
        OnTextCallback={updateGrid}
        DateCallBack={updateGrid}
      />
const updateGrid = (data) => {
    if (Array.isArray(newDataHere) && newDataHere?.length > 0) {
      
      // newDataHere is an array of data
      const tempData = newDataHere;
      tempData.map((x) => {
        if (data.id === x.id) {
          x.name = data.textVal;
        }
        if (data.id === x.id) {
          x.Establish = data.dateVal;
        }
      });
      setDataAll(tempData);
    }
    console.log("tempdataNew", dataAll);
  };

As seen from above code, both text and date has similar id which is received from Grid, but, when changed one field shows undefined for another field. How can this be tackled?

Please refer to codesandbox --> https://codesandbox.io/s/jovial-aryabhata-95o2sy?file=/src/Table.js

CodePudding user response:

Your Grid component only returns dateVal or textVal with each kind of value change, so you cannot change them both together.

For the fix, you can add a condition to check your value availabilities from each value change

  const updateGrid = (data) => {
    if (Array.isArray(newDataHere) && newDataHere?.length > 0) {
      const tempData = newDataHere;
      tempData.forEach((x) => {
        if (data.id === x.id) {
          //if textVal is available, we will update
          if (data.textVal) {
            x.name = data.textVal;
          }
          //if dateVal is available, we will update
          if (data.dateVal) {
            x.Establish = data.dateVal;
          }
        }
      });
      setDataAll(tempData);
    }
    console.log("tempdataNew", dataAll);
  };

The sandbox link

  • Related