0

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... ?

emsiiggy
  • 343
  • 1
  • 2
  • 13

2 Answers2

2

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...

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • Okay, so the "someMethod" will know that i want to change only "name" ? It will not behave in a such way that i passed "name" as "state" and now i can do some weird things? And i've got second question - Do i need return statement in "someMethod" ? Or it works like that: If i have colon with the variable then i dont need return, but if i dont then i need it ? I'm pretty new in react and trying to understand it... – emsiiggy Nov 18 '19 at 18:07
  • @emsiiggy - When you give an object to `setState`, it merges that object's properties with the current state. So yes, `someMethod` will change just `name` and leave other things alone. Re your second question: You have to return an object. All of the methods in the answer return an object. The one that doesn't have a `return` keyword in it is a *concise-form arrow function* (the first character after the `=>` isn't a `{`), and so it implicitly returns the result of the expression in it. More here: https://stackoverflow.com/questions/45754957/why-doesnt-my-arrow-function-return-a-value – T.J. Crowder Nov 18 '19 at 18:11
0

Since you're doing this in setState your method works and will merge the updated name with the rest of your state.

Matt Croak
  • 2,788
  • 2
  • 17
  • 35