Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
125
rated 0 times [  127] [ 2]  / answers: 1 / hits: 45552  / 9 Years ago, fri, january 22, 2016, 12:00:00

For a plugin I'm using I have to have a state that looks like this:



getInitialState() {
return {
invalid: true,
access: {
access_code: '',
zipcode: '',
password: '',
confirm: '',
hospital_id: '',
},
}
},


How would I set the state of hospital_id without setting the rest of access?



This seems to remove everything but hospital_id:



this.setState({access: {hospital_id: 1}})

More From » reactjs

 Answers
17

You have a few options:




  1. With ECMA6, you can use the Object spread proposal (...) to create copies of objects with updated properties.



    this.setState({
    access: {
    ...this.state.access,
    hospital_id: 1,
    },
    });

  2. You can use the native assign function on the Object (Object.assign())



    this.setState({
    access: Object.assign({}, this.state.access, {
    hospital_id: 1,
    }),
    });

  3. Or for the shortest version and atomic update:



     this.setState(({access}) => ({access: {
    ...access,
    hospital_id: 1,
    }});

  4. And one more option is the updates addon:



    var update = require('react-addons-update');
    // per React docs
    // https://reactjs.org/docs/update.html
    // , you may want to change this to
    // import update from 'immutability-helper';
    this.setState({
    access: update(this.state.access, {
    hospital_id: {$set: 1},
    })
    });



I would recommend using the first one.


[#63602] Thursday, January 21, 2016, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
brandensebastiand

Total Points: 323
Total Questions: 115
Total Answers: 106

Location: China
Member since Mon, Aug 22, 2022
2 Years ago
;