Reputation: 343
My question is how to update one field in react state (if i have more than one) e.g.:
class TestingClass extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "",
lastname: "something"
};
}
};
And now in some method i run from render()
someMethod = () => {
this.setState(state => {
const newName = state.name + " 0 ";
return { newName };
});
};
And now the state will only have one field (name), lastname will disappear. Or am i wrong... ?
Upvotes: 0
Views: 2214
Reputation: 1074305
And now the state will only have one field (name), lastname will disappear.
No, setState
merges the object you provide with the existing state. In your code, your state object will end up having name
, lastname
, and newName
(because that's the name you've used in the object you return from the setState
callback).
If you want to update name
, you need to use the name name
in the new object you're returning:
someMethod = () => {
this.setState(state => {
const name = state.name + " 0 ";
return { name };
});
};
Side note: That code can be more concise if you want, using a concise arrow function and destructuring:
someMethod = () => {
this.setState(({name}) => ({ name: name + " 0"}));
};
or using just destructuring but keeping the function body on the arrow function:
someMethod = () => {
this.setState(({name}) => {
name += " 0";
return { name };
}
};
I'm not advocating it (minifying is for minifiers), but it's useful to know...
Upvotes: 2
Reputation: 2888
Since you're doing this in setState
your method works and will merge the updated name
with the rest of your state.
Upvotes: 0