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 !
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 !
Share Improve this question asked Sep 27, 2018 at 13:15 Clément CREUSATClément CREUSAT 3213 gold badges6 silver badges13 bronze badges 6 | Show 1 more comment1 Answer
Reset to default 15this 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
)
setState()
change takes effect (reactjs.org/docs/react-component.html#setstate - it shows how it may not do it immediately, batch it of defer it for later). so other parts of the app may get the changed values before they should. it's acceptable to doconst result = Object.assign({}, this.state.result);
to avoid mutating it directly (or spread). – Dimitar Christoff Commented Sep 27, 2018 at 14:17