André André - 1 month ago 23
React JSX Question

React native setState with multiple values

I'm defining my state in constructor like this.

constructor(props) {
super(props);
this.state = {
order: props.data ? { ...props.data } : { title: '', birthdate: '' , gender: '', startdate: '', starttime: '', brand: null},


Then in another function i'm trying to setState only for order.brand

this.setState({
//order: { brand: items[0].title },
order: { ...order, brand: items[0].title },
});


The commented line is overwriting all elements, and the second returns that order is not defined.

What's the correct syntax to save just one item of the state that have multiple values.

Answer

As mentioned in the comments you can use update to modify object values:

var update = require('react-addons-update');

this.setState(function(previousState, currentProps) {
    var newState = update(previousState,{
        order: {
            brand: {
                $set: 'some new value'
            }
        }
    });

    return newState;
});

see https://facebook.github.io/react/docs/update.html

Comments