Skip to content Skip to sidebar Skip to footer

Unexpected Outcome When Modifying An Object In A Function

I am getting a weird outcome when i modify an object within a function, the funny thing is that when i do the same thing in a browser console i get what i am expecting but in react

Solution 1:

The problem is you modified the i which points to the original object A. To solve it, just "clone" the i:

Example:

constmakeChanges = ({ ...i }) => {
  i.foo = "test";
  i["new"] = "i am new";

  return i;
};

Or

constmakeChanges = (i) => {
  const result = { ...i };
  // or// const result = Object.assign({}, i);
  result.foo = "test";
  result["new"] = "i am new";

  return result;
};

Or

constmakeChanges = (i) => {
  return { ...i, foo: "test", "new": "i am new" } ;
};

The working example: https://codesandbox.io/s/blue-wave-mhnpp

See the spread (...) syntax: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

Solution 2:

I think rendering the output is async. And console.log keep reference of the objects it has to print. we also know if we are passing object as function attribute then it will b pass by reference So In this code object A has some address(say abc) to which it refer. And value at abc is value of object A When u pass A in function makeChanges the value at address abc got changed and console has to print the value at abc that's why same values are logged as at address abc value is same If u want to see difference then u can make deep copy of object by Object.assign

constmakeChanges = i => {
  i.foo = "test";
  i["new"] = "i am new";

  return i;
};

functionApp() {
  var A = {
    foo: "foo",
    bar: "bar"
  };

  console.log(A);

  A = makeChanges(Object.assign({},A));

  console.log(A);
  //the render code...
}

output will b

Object {foo: "foo", bar: "bar"}
Object {foo: "test", bar: "bar", new: "i am new"}

By Object.assign({},A) U are creating new object at different memory so change this will not affect the value at memory abc (abc example)

Post a Comment for "Unexpected Outcome When Modifying An Object In A Function"