how to copy the value of the state of a component into a variable

3

I have an initial state with objeto item to save the character data. equal const model = this.state.item to be able to obtain the object and make modifications but it seems to create a reference and not a copy. when I modify var body which is the object I use to delete and add model elements, this is also modified this.state.item

  net.on('click', ev => {
  if (!ev.shape) {
    const model =  this.state.item
    var body = model.item.getModel()
    delete body.shape;
    const perid = body.id;
    delete body.id;
    body.per_id = perid;
    body.source = perid;
    var params = {
      headers: {
        "Content-Type": "application/json"
      },
      method: "POST",
      body
    }
    cfetch(params);

The problem I have is that when I get the this.state.item it is modified and I want it not to change just making a copy in const model .

    
asked by juan camilo caviedes 31.05.2018 в 23:23
source

4 answers

1

You said it, you get a reference so you're still using the same object.

The solution in this case is to make a deep copy of the object so you will be cloning its properties.

There is a library lodash that allows you to do this in a simple way.

p>

to add it to the project npm install -s lodash.clonedeep and use it in this way.

 import cloneDeep from 'lodash/cloneDeep';

 const model = cloneDeep(this.state.item);
 var body = model.item.getModel()
 delete body.shape;
    
answered by 01.06.2018 / 01:25
source
1

If you are programming in ES6 you can use deconstruct:

const model = { ...this.state.item };

You can also do it with the Object.assign function:

const model = Object.assign({}, this.state.item);

Using deconstruct you could simplify the code further:

const { item: model } = this.state;

On the other hand, as in your code you only use the "model" variable once, you could delete it and go directly to the getModel method:

const { item: { item: { getModel } } =  this.state;
const body = { ...getModel() }
    
answered by 11.01.2019 в 23:51
0

As you said when assigning an object to a variable, it creates a reference instead of a copy.

If you want to make a copy of an object you can use Object.assing() , and pass an empty object as the first parameter to create an exact copy, a functional example adapted from the MDN example:

const object1 = {
  a: 1,
  b: 2,
  c: 3
};

// Copia
const object2 = Object.assign({}, object1);

// Referencia
const object3 = object1;

object3.c = 4;

console.log(object1.c, object2.c, object3.c);
    
answered by 01.06.2018 в 01:46
0

If the object has no circular references and without using external libraries:

const nuevoObjeto = JSON.parse(JSON.stringify(objetoOriginal));
    
answered by 11.07.2018 в 12:27