Kramer
Kramer

Reputation: 399

Cloning Object properties/values Directly

I want to clone object properties value into a null variable or empty object. I don't know whether we can achieve it or not therefore I am having this doubt I searched but didn't get a solution

event has keys --> firstName, lastName and age

I have tried to set state directly using set state method

this.setState({currentEvent:event});

Here is the complete code:

   this.state = {
      dialogEvent:false,
      currentEvent:{},
    }

  }

  handleClickButton = event => {
   // event is the single event that needs to be updated in parent event 
     after updating age.

  console.log(event);

  axios.get(configs.Data.getNewAge)
  .then(res=>{
       console.log(res); // res.data.newObj has time date and time epoch

       Object.keys(event).forEach(function(index){
            console.log(index);
       }); // checking the keys for event by logging

     this.setState({currentEvent:event});

       this.setState({eventDialog:true}); // this is the dialog
  }).catch((e)=>console.log("Error :"+e));


  };

Actual Results: currentEvent is undefined if fetched in dialog

Expected Results: it should have cloned all properties and values

Upvotes: 1

Views: 49

Answers (2)

mbojko
mbojko

Reputation: 14679

Try cloning the event object.

  handleClickButton = event => {
  const currentEvent = Object.assign({}, event);

  axios.get(configs.Data.getNewAge)
  .then(res => {
     this.setState({currentEvent});

  }).catch((e)=>console.log("Error :"+e));

  };

Upvotes: 1

holydragon
holydragon

Reputation: 6728

Use spread.

const event = {firstName:"fn",lastName:"ln",age:99}
let currentEvent = {...event}
console.log(currentEvent)

Upvotes: 2

Related Questions