Add new Key/Value into Object in React Native
14,303
this should work fine.
this.setState({
result: {
...this.state.result,
[id]: value
}
});
it uses modern/new features such as object spread (...this.state.result
) and dynamic object properties ([id]: value
)
Author by
Clément CREUSAT
Updated on June 09, 2022Comments
-
Clément CREUSAT almost 2 years
I'm working on a React Native project. Right now, I'm adding new key/value inside an object.
It's working but I would like to know if there is a better way to do it or if you have any advice.
I'm still new to ReactJS/React Native and not 100% skills on Javascript. So here's my code :
My object
state = { result : { "q1":1 } }
My function to add key/value and modify the state of
result
:_getValue = (id, value) => { var newObj = this.state.result; newObj[id] = parseInt(value); this.setState({ result: newObj }, () => { console.log(this.state.result) }) }
Thank you !
-
Clément CREUSAT over 5 yearsThank you ! I got it about the immutable state. I don't know why I did this ... I did the right thing in another component but I completely forgot :-)