4

I have for example this :

this.state = {
      lang1: { name: 'Anglais', code: "en" },
      lang2: { name: 'Français', code: "fr" }
};

How can I setState the lang1.name? It doesn't work when I do:

this.setState({ lang1.name: "myExample" });

I'm new in React Native and I didn't understand that clearly

Mayank Shukla
  • 100,735
  • 18
  • 158
  • 142
Erased
  • 571
  • 4
  • 10
  • 22
  • Possible duplicate of [How to update object in React state](https://stackoverflow.com/questions/36650570/how-to-update-object-in-react-state) – Mayank Shukla Jun 15 '17 at 08:23
  • If you search this ques **how to update the object in state**, you will find so many results for the same ques, before asking once check whether that ques has been asked or not. check this also: https://stackoverflow.com/questions/29537299/react-how-do-i-update-state-item1-on-setstate-with-jsfiddle – Mayank Shukla Jun 15 '17 at 08:26
  • I agree with @MayankShukla – Ritesh Bansal Jun 15 '17 at 08:26

4 Answers4

11

You can just do this. ... just adds exiting keys and then adds/overwrites new ones

this.setState({
 lang1:{
  ...this.state.lang1,
  name: "myExample"
 }
})
Chetan
  • 945
  • 1
  • 5
  • 14
5
this.setState({
  lang1: {
    name: "myExample",
    code: this.state.lang1.code
  }
});
ashmna
  • 95
  • 1
  • 9
  • 2
    You should explain why this works instead of just giving a code-only answer. As it stands, this answer doesn't do much to help the OP or future visitors understand what's happening. You could also use the ES6 `...` spread operator to make your example more applicable to general scenarios – Bojangles Jun 15 '17 at 08:33
  • @Bojangles you are right and I think this answer is more helpful https://stackoverflow.com/a/44562452/2674187, and about the reason, in js yo can't have object's key like this `lang1.name`, you can have `'lang1.name'` bit ist is not mine that it is the nested object, it just sting with dot – ashmna Jun 15 '17 at 08:43
  • Yeah, before seeing your post I solved my solution. But thanks for the explanation, I understand more :) – Erased Jun 15 '17 at 13:11
2

You can do it like this:

this.setState((previousState) => {
  const lang1 = previousState.lang1
  return {...lang1, name: 'myExample'}
})
Ritesh Bansal
  • 3,108
  • 2
  • 16
  • 23
0

Value is a parameter...

let data = this.state.objectState
data[prop] = value
this.setState({objectState: data})
Regolith
  • 2,944
  • 9
  • 33
  • 50