Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the name of the state object not need to match the name in setState?

In the following code you'll see that I've whimsically named my this.state object 'gladys'. In the handleSubmit function a value is returned by the const result but I set the name of the object here to the much more logical 'errormessage'. Why does this work? Why does the name of the object whose initial state is defined in this.state not have to match the name of the object which is updated by this.setState? (just in case it's not obvious, handleAddOption runs validation on the optionfield value and returns an error message if newoption either equals an empty string or already exists.)

class AddOption extends React.Component {
constructor(props){
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.state = {
        gladys: undefined
    }
}
handleSubmit(e) {
    e.preventDefault();
    const newoption = e.target.elements.optionfield.value.trim();
    const result = this.props.handleAddOptions(newoption);
    e.target.elements.optionfield.value = '';

    this.setState((prevState) => ({ 
        errormessage: result
    }));
}
render () {
    return (
        <div>
        {this.state.errormessage && <p>{this.state.errormessage}</p>}
        <form onSubmit={this.handleSubmit}>
        <input type='text' name='optionfield'/>
        <button>Add an Option</button>
        </form>
        </div>
    );
}

}

like image 659
Will Dove Avatar asked Jan 20 '26 03:01

Will Dove


2 Answers

It works because this

this.state = {
    gladys: undefined
}

and this

this.state = {
    gladys: undefined,
    errormessage: undefined
}

are equal in JavaScript.

So when you do

this.setState({ errormessage: result })

React just replaces

errormessage: undefined

with

errormessage: result

You should also note that gladys is not the name of the state but a property of the state.

A component's state can contain several properties, for example gladys and errormessage.

like image 155
GG. Avatar answered Jan 22 '26 05:01

GG.


This is possible because setState shallowly merges the returned object with the state object, this behavior allows partial updates on the state, such as the one in your example.

// Let's say that the current state looks like this
this.state = { someProp: 'someValue', anotherProp: 'anotherValue' };

// Calling set state like this
this.setState((prevState) => ({ 
    errormessage: 'result'
}));

// Means that you are merging the prevState, shown above, into a new
// State object wich will contain the errormessage prop
this.state = { 
    someProp: 'someValue', 
    anotherProp: 'anotherValue',
    errormessage: 'result',
};

Here is a link to the official documentation about setState

like image 20
Julian Avatar answered Jan 22 '26 05:01

Julian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!