angry kiwi
angry kiwi

Reputation: 11435

reactjs how to update state

constructor(){
    super();
    this.state = { 
        address: {
            street:null,
            city:null,
            postalCode: null
        }
    };
}
postalCodeChange(e){
    this.setState.address.postalCode = e.target.value;
    console.log(this.state);
}

I'm trying to update the state, but the postalCode only. When the above code execute, I expect to get something like this

Object {address: Object {
           street: null,
           city: null,
           postalCode: 'some new value'
} }

But I got error. What's wrong?

Upvotes: 3

Views: 3093

Answers (2)

Oleksandr T.
Oleksandr T.

Reputation: 77482

In order to update state you must use setState method

const state = merge({}, this.state, {
  address: { postalCode: e.target.value }
});

this.setState(state);

Note - merge it is not real function, in order to deep merge objects you can use packages like merge-deep, assign-deep

or you can use update method from React.addons, to get this method do the following steps

  1. npm i react-addons-update --save
  2. import(or require) and use it

    import update from 'react-addons-update';
    const state = update(this.state, {
      address: { 
        postalCode: { $set: e.target.value }
      }
    });     
    
    this.setState(state);
    

Example

also if you use ES2015 you can use Object.assign, or spread operator

Object.assign:

const state = Object.assign({}, this.state, {
   address: Object.assign({}, this.state.address, { postalCode: 1000 })
});

spread operator

const newState = {
  address: { ...state.address, postalCode: 1000 }
};

Upvotes: 5

Kai Hao
Kai Hao

Reputation: 689

I saw that you are using ES6, so I'm assuming you can also use the stage-2 object spread operator.

By using that feature, you can update your state without additional plugin or lots of code.

this.setState({
    address: {
        ...this.state.address,
        postalCode: e.target.value
    }
});

Upvotes: 2

Related Questions