Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialMichael Robb
7,727 PointsCalling setState() in React with an object that only has some of the original state object's properties.
In previous React Treehouse videos I've only seen setState() called with an object that has all of the original state object's properties. I then found it confusing in the React by example | Filtering Guests video because the toggleFilter() function calls setState() with an object that only has part of the original state's properties - {isFiltered: !this.state.isFiltered} but no 'guest' array. It was my understanding that when setState() is called with an object it does a replacement of the original state object. Meaning if you called it with {isFiltered: !this.state.isFiltered} it would result in a new state object that has an 'isFiltered' property but no 'guests' array. It looks like this isn't the case though, that it just does a find and replace based on what properties are included in the object that gets passed to setState(). Is this correct?
1 Answer
Robert Schaap
19,836 PointsIf have to guess a bit because there's no link to the original video, but basically setState()
mutates whatever part of the state you feed it. So if you have a state of
state = {
firstName: "",
lastName: ""
}
and in some onClick
function you call this.setState({ firstName: "Michael" })
, you would only changing the firstName
property of the state, since setState
allows you to target just pieces of the state. It gets more complicated when you have stuff nested inside of properties, but basic targeting is pretty straight forward.
Does that answer your question?