Arashigor
Arashigor

Reputation: 171

Strange js object's field behaviour in Chrome

I'm trying to reassign targetRow's field with variable converted from String to Number, but Chrome's console gives me some strange output:

  targetRow[fieldName] = Number(value);
  console.log(targetRow[fieldName]);                  // => 12
  console.log(targetRow[fieldName]===Number(value));  // => true
  console.log(targetRow);

enter image description here

When this object is passed to the state, it behaves as like field's value is undefined.

let execPlanTmp = this.state.execPlan.slice();
execPlanTmp[rowIdx] = targetRow;
this.setState({execPlan: execPlanTmp});
console.log(this.state.execPlan);

enter image description here

Upd: JSON.stringify(targetRow) returns the correct string, which is passed to the server, but js object's field is still treated as undefined by React and Chrome.

Upd 2 This is the whole function:

onCellEdit = (row, fieldName, value) => {
    let rowId = this.state.execPlan.indexOf(row);

    if (rowId >= 0) {
        let execPlanTmp = this.state.execPlan.slice();
        execPlanTmp[rowId][fieldName] = Number(value);
        this.setState({execPlan: execPlanTmp});

        fetch("http://localhost:8080/api", {
            method: "PUT",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify(execPlanTmp[rowId]),
            mode: "cors"
        });
    }
};

Upvotes: 1

Views: 50

Answers (1)

Nestor Yanchuk
Nestor Yanchuk

Reputation: 1246

I met this issue once. It is because when you do console.log(someVar) it does not literally mean "make text from someVar and print it", it shows you the value that is stored in the memory by the moment you click collapsed ({...}) array, so if the value has changed before you click but after console.log() it changes in console.

Run next code in the console and you will understand:

var arr = [];
for (var i = 0; i < 1000; i++) {
    arr.push({a: i, b: 0});
}
console.log(arr);
console.log(JSON.stringify(arr).substr(0, 700));
for (var j in arr){
  arr[j].b=Math.random();
}

Output: the result

Upvotes: 1

Related Questions