Updating an object with setState in React
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}
Is it at all possible to update object's properties with setState?
Something like:
this.state = {
jasper: { name: 'jasper', age: 28 },
}
I have tried:
this.setState({jasper.name : 'someOtherName'});
and this:
this.setState({jasper:{name:'someothername'}})
The first is Syntax error and the second just does nothing. Any ideas?
reactjs state
add a comment |
Is it at all possible to update object's properties with setState?
Something like:
this.state = {
jasper: { name: 'jasper', age: 28 },
}
I have tried:
this.setState({jasper.name : 'someOtherName'});
and this:
this.setState({jasper:{name:'someothername'}})
The first is Syntax error and the second just does nothing. Any ideas?
reactjs state
3
second code would have worked however you would have lost theage
property insidejasper
.
– giorgim
Jul 10 '18 at 8:14
add a comment |
Is it at all possible to update object's properties with setState?
Something like:
this.state = {
jasper: { name: 'jasper', age: 28 },
}
I have tried:
this.setState({jasper.name : 'someOtherName'});
and this:
this.setState({jasper:{name:'someothername'}})
The first is Syntax error and the second just does nothing. Any ideas?
reactjs state
Is it at all possible to update object's properties with setState?
Something like:
this.state = {
jasper: { name: 'jasper', age: 28 },
}
I have tried:
this.setState({jasper.name : 'someOtherName'});
and this:
this.setState({jasper:{name:'someothername'}})
The first is Syntax error and the second just does nothing. Any ideas?
reactjs state
reactjs state
edited Jan 5 '18 at 15:27
Mayank Shukla
42k76787
42k76787
asked Apr 26 '17 at 15:47
JohnSnowJohnSnow
1,10431022
1,10431022
3
second code would have worked however you would have lost theage
property insidejasper
.
– giorgim
Jul 10 '18 at 8:14
add a comment |
3
second code would have worked however you would have lost theage
property insidejasper
.
– giorgim
Jul 10 '18 at 8:14
3
3
second code would have worked however you would have lost the
age
property inside jasper
.– giorgim
Jul 10 '18 at 8:14
second code would have worked however you would have lost the
age
property inside jasper
.– giorgim
Jul 10 '18 at 8:14
add a comment |
11 Answers
11
active
oldest
votes
There are multiple ways of doing this.
1- Simplest one:
First create a copy of jasper
then do the changes in that:
let jasper = Object.assign({}, this.state.jasper); //creating copy of object
jasper.name = 'someothername'; //updating value
this.setState({jasper});
Instead of using Object.assign
we can also write it like this:
let jasper = {...this.state.jasper};
2- Using spread operator:
this.setState(prevState => ({
jasper: {
...prevState.jasper,
name: 'something'
}
}))
The way I was trying now works though... the second way :S
– JohnSnow
Apr 26 '17 at 16:05
6
@JohnSnow in you second it will remove the other properties fromjasper
object, do theconsole.log(jasper)
you will see only one keyname
, age will not be there :)
– Mayank Shukla
Apr 26 '17 at 16:07
1
@JohnSnow, yes this way is proper ifjasper
is anobject
, don't the whether best or not, may be other better solutions are possible :)
– Mayank Shukla
Apr 26 '17 at 16:16
4
Good to mention here that neitherObject.assign
nor spread operator deep copy properties. In this way you should use workarounds like lodashdeepCopy
etc.
– Alex Vasilev
May 24 '18 at 8:08
1
How boutlet { jasper } = this.state
?
– Brian Le
Nov 23 '18 at 20:44
|
show 7 more comments
Fastest and the most readable way:
this.setState({...this.state.jasper, name: 'someothername'});
Althought this.state.jasper
already contain a name property, latter name: 'someothername'
with be used.
14
This solution has one big disadvantage: in order to optimize state updates React might group multiple updates. As a consequencethis.state.jasper
does not necessarily contain the latest state. Better use the notation with theprevState
.
– sinned
Jun 8 '18 at 7:55
add a comment |
Use spread operator and some ES6 here
this.setState({
jasper: {
...this.state.jasper,
name: 'something'
}
})
add a comment |
I used this solution.
If you have a nested state like this:
this.state = {
formInputs:{
friendName:{
value:'',
isValid:false,
errorMsg:''
},
friendEmail:{
value:'',
isValid:false,
errorMsg:''
}
}
you can declare the handleChange function that copy current status and re-assigns it with changed values
handleChange(el) {
let inputName = el.target.name;
let inputValue = el.target.value;
let statusCopy = Object.assign({}, this.state);
statusCopy.formInputs[inputName].value = inputValue;
this.setState(statusCopy);
}
here the html with the event listener. Make sure to use the same name used into state object (in this case 'friendName')
<input type="text" onChange={this.handleChange} " name="friendName" />
add a comment |
The first case is indeed a syntax error.
Since I can't see the rest of your component, it's hard to see why you're nesting objects in your state here. It's not a good idea to nest objects in component state. Try setting your initial state to be:
this.state = {
name: 'jasper',
age: 28
}
That way, if you want to update the name, you can just call:
this.setState({
name: 'Sean'
});
Will that achieve what you're aiming for?
For larger, more complex data stores, I would use something like Redux. But that's much more advanced.
The general rule with component state is to use it only to manage UI state of the component (e.g. active, timers, etc.)
Check out these references:
- https://facebook.github.io/react/docs/react-component.html#state
- https://facebook.github.io/react/docs/state-and-lifecycle.html
1
I only used that as an example, the object must be nested.. I probably should be using Redux but I am trying to understand React fundementals..
– JohnSnow
Apr 26 '17 at 16:07
2
Yeah, I would stay away from Redux for now. While you're learning the fundamentals, try to keep your data simple. That'll help you avoid odd cases that trip you up. 👍
– mccambridge
Apr 26 '17 at 16:39
add a comment |
try this,it should work fine
this.setState(Object.assign(this.state.jasper,{name:'someOtherName'}));
I've tried many other methods... but your snippet is rock! thanks man
– hendra1
Jan 23 at 13:14
Thank you very much for letting me know. I am happy that resolved your problem.
– Burak Kahraman
Jan 24 at 15:37
add a comment |
Another option: define your variable out of the Jasper object and then just call a variable.
Spread operator: ES6
this.state = { jasper: { name: 'jasper', age: 28 } }
let foo = "something that needs to be saved into state"
this.setState(prevState => ({
jasper: {
...jasper.entity,
foo
}
})
1
I am not sure the downvoter(s) understood thatfoo
expands tofoo: foo
...
– Cory Silva
Dec 8 '18 at 16:55
add a comment |
Also, following Alberto Piras solution, if you don't want to copy all the "state" object:
handleChange(el) {
let inputName = el.target.name;
let inputValue = el.target.value;
let jasperCopy = Object.assign({}, this.state.jasper);
jasperCopy[inputName].name = inputValue;
this.setState({jasper: jasperCopy});
}
add a comment |
You can try with this:
(Note: name of input tag === field of object)
<input name="myField" type="text"
value={this.state.myObject.myField}
onChange={this.handleChangeInpForm}></input>
-----------------------------------------------------------
handleChangeInpForm = (e) => {
let newObject = this.state.myObject;
newObject[e.target.name] = e.target.value;
this.setState({
myObject: newObject
})
}
Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer
– Elletlar
Jan 28 at 12:51
add a comment |
Simple and dynamic way.
This will do the job, but you need to set all the ids to the parent so the parent will point to the name of the object, being id = "jasper" and name the name of the input element = property inside of the object jasper.
handleChangeObj = ({target: { id , name , value}}) => this.setState({ [id]: { ...this.state[id] , [name]: value } });
add a comment |
You can try with this:
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState.name = 'someOtherName';
return {jasper: prevState}
})
or for other property:
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState.age = 'someOtherAge';
return {jasper: prevState}
})
Or you can use handleChage function:
handleChage(event) {
const {name, value} = event.target;
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState[name] = value;
return {jasper: prevState}
})
}
and HTML code:
<input
type={"text"}
name={"name"}
value={this.state.jasper.name}
onChange={this.handleChange}
/>
<br/>
<input
type={"text"}
name={"age"}
value={this.state.jasper.age}
onChange={this.handleChange}
/>
add a comment |
protected by Community♦ Mar 14 at 18:31
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
11 Answers
11
active
oldest
votes
11 Answers
11
active
oldest
votes
active
oldest
votes
active
oldest
votes
There are multiple ways of doing this.
1- Simplest one:
First create a copy of jasper
then do the changes in that:
let jasper = Object.assign({}, this.state.jasper); //creating copy of object
jasper.name = 'someothername'; //updating value
this.setState({jasper});
Instead of using Object.assign
we can also write it like this:
let jasper = {...this.state.jasper};
2- Using spread operator:
this.setState(prevState => ({
jasper: {
...prevState.jasper,
name: 'something'
}
}))
The way I was trying now works though... the second way :S
– JohnSnow
Apr 26 '17 at 16:05
6
@JohnSnow in you second it will remove the other properties fromjasper
object, do theconsole.log(jasper)
you will see only one keyname
, age will not be there :)
– Mayank Shukla
Apr 26 '17 at 16:07
1
@JohnSnow, yes this way is proper ifjasper
is anobject
, don't the whether best or not, may be other better solutions are possible :)
– Mayank Shukla
Apr 26 '17 at 16:16
4
Good to mention here that neitherObject.assign
nor spread operator deep copy properties. In this way you should use workarounds like lodashdeepCopy
etc.
– Alex Vasilev
May 24 '18 at 8:08
1
How boutlet { jasper } = this.state
?
– Brian Le
Nov 23 '18 at 20:44
|
show 7 more comments
There are multiple ways of doing this.
1- Simplest one:
First create a copy of jasper
then do the changes in that:
let jasper = Object.assign({}, this.state.jasper); //creating copy of object
jasper.name = 'someothername'; //updating value
this.setState({jasper});
Instead of using Object.assign
we can also write it like this:
let jasper = {...this.state.jasper};
2- Using spread operator:
this.setState(prevState => ({
jasper: {
...prevState.jasper,
name: 'something'
}
}))
The way I was trying now works though... the second way :S
– JohnSnow
Apr 26 '17 at 16:05
6
@JohnSnow in you second it will remove the other properties fromjasper
object, do theconsole.log(jasper)
you will see only one keyname
, age will not be there :)
– Mayank Shukla
Apr 26 '17 at 16:07
1
@JohnSnow, yes this way is proper ifjasper
is anobject
, don't the whether best or not, may be other better solutions are possible :)
– Mayank Shukla
Apr 26 '17 at 16:16
4
Good to mention here that neitherObject.assign
nor spread operator deep copy properties. In this way you should use workarounds like lodashdeepCopy
etc.
– Alex Vasilev
May 24 '18 at 8:08
1
How boutlet { jasper } = this.state
?
– Brian Le
Nov 23 '18 at 20:44
|
show 7 more comments
There are multiple ways of doing this.
1- Simplest one:
First create a copy of jasper
then do the changes in that:
let jasper = Object.assign({}, this.state.jasper); //creating copy of object
jasper.name = 'someothername'; //updating value
this.setState({jasper});
Instead of using Object.assign
we can also write it like this:
let jasper = {...this.state.jasper};
2- Using spread operator:
this.setState(prevState => ({
jasper: {
...prevState.jasper,
name: 'something'
}
}))
There are multiple ways of doing this.
1- Simplest one:
First create a copy of jasper
then do the changes in that:
let jasper = Object.assign({}, this.state.jasper); //creating copy of object
jasper.name = 'someothername'; //updating value
this.setState({jasper});
Instead of using Object.assign
we can also write it like this:
let jasper = {...this.state.jasper};
2- Using spread operator:
this.setState(prevState => ({
jasper: {
...prevState.jasper,
name: 'something'
}
}))
edited Sep 7 '17 at 14:03
answered Apr 26 '17 at 15:59
Mayank ShuklaMayank Shukla
42k76787
42k76787
The way I was trying now works though... the second way :S
– JohnSnow
Apr 26 '17 at 16:05
6
@JohnSnow in you second it will remove the other properties fromjasper
object, do theconsole.log(jasper)
you will see only one keyname
, age will not be there :)
– Mayank Shukla
Apr 26 '17 at 16:07
1
@JohnSnow, yes this way is proper ifjasper
is anobject
, don't the whether best or not, may be other better solutions are possible :)
– Mayank Shukla
Apr 26 '17 at 16:16
4
Good to mention here that neitherObject.assign
nor spread operator deep copy properties. In this way you should use workarounds like lodashdeepCopy
etc.
– Alex Vasilev
May 24 '18 at 8:08
1
How boutlet { jasper } = this.state
?
– Brian Le
Nov 23 '18 at 20:44
|
show 7 more comments
The way I was trying now works though... the second way :S
– JohnSnow
Apr 26 '17 at 16:05
6
@JohnSnow in you second it will remove the other properties fromjasper
object, do theconsole.log(jasper)
you will see only one keyname
, age will not be there :)
– Mayank Shukla
Apr 26 '17 at 16:07
1
@JohnSnow, yes this way is proper ifjasper
is anobject
, don't the whether best or not, may be other better solutions are possible :)
– Mayank Shukla
Apr 26 '17 at 16:16
4
Good to mention here that neitherObject.assign
nor spread operator deep copy properties. In this way you should use workarounds like lodashdeepCopy
etc.
– Alex Vasilev
May 24 '18 at 8:08
1
How boutlet { jasper } = this.state
?
– Brian Le
Nov 23 '18 at 20:44
The way I was trying now works though... the second way :S
– JohnSnow
Apr 26 '17 at 16:05
The way I was trying now works though... the second way :S
– JohnSnow
Apr 26 '17 at 16:05
6
6
@JohnSnow in you second it will remove the other properties from
jasper
object, do the console.log(jasper)
you will see only one key name
, age will not be there :)– Mayank Shukla
Apr 26 '17 at 16:07
@JohnSnow in you second it will remove the other properties from
jasper
object, do the console.log(jasper)
you will see only one key name
, age will not be there :)– Mayank Shukla
Apr 26 '17 at 16:07
1
1
@JohnSnow, yes this way is proper if
jasper
is an object
, don't the whether best or not, may be other better solutions are possible :)– Mayank Shukla
Apr 26 '17 at 16:16
@JohnSnow, yes this way is proper if
jasper
is an object
, don't the whether best or not, may be other better solutions are possible :)– Mayank Shukla
Apr 26 '17 at 16:16
4
4
Good to mention here that neither
Object.assign
nor spread operator deep copy properties. In this way you should use workarounds like lodash deepCopy
etc.– Alex Vasilev
May 24 '18 at 8:08
Good to mention here that neither
Object.assign
nor spread operator deep copy properties. In this way you should use workarounds like lodash deepCopy
etc.– Alex Vasilev
May 24 '18 at 8:08
1
1
How bout
let { jasper } = this.state
?– Brian Le
Nov 23 '18 at 20:44
How bout
let { jasper } = this.state
?– Brian Le
Nov 23 '18 at 20:44
|
show 7 more comments
Fastest and the most readable way:
this.setState({...this.state.jasper, name: 'someothername'});
Althought this.state.jasper
already contain a name property, latter name: 'someothername'
with be used.
14
This solution has one big disadvantage: in order to optimize state updates React might group multiple updates. As a consequencethis.state.jasper
does not necessarily contain the latest state. Better use the notation with theprevState
.
– sinned
Jun 8 '18 at 7:55
add a comment |
Fastest and the most readable way:
this.setState({...this.state.jasper, name: 'someothername'});
Althought this.state.jasper
already contain a name property, latter name: 'someothername'
with be used.
14
This solution has one big disadvantage: in order to optimize state updates React might group multiple updates. As a consequencethis.state.jasper
does not necessarily contain the latest state. Better use the notation with theprevState
.
– sinned
Jun 8 '18 at 7:55
add a comment |
Fastest and the most readable way:
this.setState({...this.state.jasper, name: 'someothername'});
Althought this.state.jasper
already contain a name property, latter name: 'someothername'
with be used.
Fastest and the most readable way:
this.setState({...this.state.jasper, name: 'someothername'});
Althought this.state.jasper
already contain a name property, latter name: 'someothername'
with be used.
answered Apr 17 '18 at 2:47
mannokmannok
361313
361313
14
This solution has one big disadvantage: in order to optimize state updates React might group multiple updates. As a consequencethis.state.jasper
does not necessarily contain the latest state. Better use the notation with theprevState
.
– sinned
Jun 8 '18 at 7:55
add a comment |
14
This solution has one big disadvantage: in order to optimize state updates React might group multiple updates. As a consequencethis.state.jasper
does not necessarily contain the latest state. Better use the notation with theprevState
.
– sinned
Jun 8 '18 at 7:55
14
14
This solution has one big disadvantage: in order to optimize state updates React might group multiple updates. As a consequence
this.state.jasper
does not necessarily contain the latest state. Better use the notation with the prevState
.– sinned
Jun 8 '18 at 7:55
This solution has one big disadvantage: in order to optimize state updates React might group multiple updates. As a consequence
this.state.jasper
does not necessarily contain the latest state. Better use the notation with the prevState
.– sinned
Jun 8 '18 at 7:55
add a comment |
Use spread operator and some ES6 here
this.setState({
jasper: {
...this.state.jasper,
name: 'something'
}
})
add a comment |
Use spread operator and some ES6 here
this.setState({
jasper: {
...this.state.jasper,
name: 'something'
}
})
add a comment |
Use spread operator and some ES6 here
this.setState({
jasper: {
...this.state.jasper,
name: 'something'
}
})
Use spread operator and some ES6 here
this.setState({
jasper: {
...this.state.jasper,
name: 'something'
}
})
edited Oct 5 '18 at 3:15
Just code
10.5k53267
10.5k53267
answered May 21 '18 at 9:57
NikhilNikhil
368211
368211
add a comment |
add a comment |
I used this solution.
If you have a nested state like this:
this.state = {
formInputs:{
friendName:{
value:'',
isValid:false,
errorMsg:''
},
friendEmail:{
value:'',
isValid:false,
errorMsg:''
}
}
you can declare the handleChange function that copy current status and re-assigns it with changed values
handleChange(el) {
let inputName = el.target.name;
let inputValue = el.target.value;
let statusCopy = Object.assign({}, this.state);
statusCopy.formInputs[inputName].value = inputValue;
this.setState(statusCopy);
}
here the html with the event listener. Make sure to use the same name used into state object (in this case 'friendName')
<input type="text" onChange={this.handleChange} " name="friendName" />
add a comment |
I used this solution.
If you have a nested state like this:
this.state = {
formInputs:{
friendName:{
value:'',
isValid:false,
errorMsg:''
},
friendEmail:{
value:'',
isValid:false,
errorMsg:''
}
}
you can declare the handleChange function that copy current status and re-assigns it with changed values
handleChange(el) {
let inputName = el.target.name;
let inputValue = el.target.value;
let statusCopy = Object.assign({}, this.state);
statusCopy.formInputs[inputName].value = inputValue;
this.setState(statusCopy);
}
here the html with the event listener. Make sure to use the same name used into state object (in this case 'friendName')
<input type="text" onChange={this.handleChange} " name="friendName" />
add a comment |
I used this solution.
If you have a nested state like this:
this.state = {
formInputs:{
friendName:{
value:'',
isValid:false,
errorMsg:''
},
friendEmail:{
value:'',
isValid:false,
errorMsg:''
}
}
you can declare the handleChange function that copy current status and re-assigns it with changed values
handleChange(el) {
let inputName = el.target.name;
let inputValue = el.target.value;
let statusCopy = Object.assign({}, this.state);
statusCopy.formInputs[inputName].value = inputValue;
this.setState(statusCopy);
}
here the html with the event listener. Make sure to use the same name used into state object (in this case 'friendName')
<input type="text" onChange={this.handleChange} " name="friendName" />
I used this solution.
If you have a nested state like this:
this.state = {
formInputs:{
friendName:{
value:'',
isValid:false,
errorMsg:''
},
friendEmail:{
value:'',
isValid:false,
errorMsg:''
}
}
you can declare the handleChange function that copy current status and re-assigns it with changed values
handleChange(el) {
let inputName = el.target.name;
let inputValue = el.target.value;
let statusCopy = Object.assign({}, this.state);
statusCopy.formInputs[inputName].value = inputValue;
this.setState(statusCopy);
}
here the html with the event listener. Make sure to use the same name used into state object (in this case 'friendName')
<input type="text" onChange={this.handleChange} " name="friendName" />
answered Mar 6 '18 at 10:29
Alberto PirasAlberto Piras
9113
9113
add a comment |
add a comment |
The first case is indeed a syntax error.
Since I can't see the rest of your component, it's hard to see why you're nesting objects in your state here. It's not a good idea to nest objects in component state. Try setting your initial state to be:
this.state = {
name: 'jasper',
age: 28
}
That way, if you want to update the name, you can just call:
this.setState({
name: 'Sean'
});
Will that achieve what you're aiming for?
For larger, more complex data stores, I would use something like Redux. But that's much more advanced.
The general rule with component state is to use it only to manage UI state of the component (e.g. active, timers, etc.)
Check out these references:
- https://facebook.github.io/react/docs/react-component.html#state
- https://facebook.github.io/react/docs/state-and-lifecycle.html
1
I only used that as an example, the object must be nested.. I probably should be using Redux but I am trying to understand React fundementals..
– JohnSnow
Apr 26 '17 at 16:07
2
Yeah, I would stay away from Redux for now. While you're learning the fundamentals, try to keep your data simple. That'll help you avoid odd cases that trip you up. 👍
– mccambridge
Apr 26 '17 at 16:39
add a comment |
The first case is indeed a syntax error.
Since I can't see the rest of your component, it's hard to see why you're nesting objects in your state here. It's not a good idea to nest objects in component state. Try setting your initial state to be:
this.state = {
name: 'jasper',
age: 28
}
That way, if you want to update the name, you can just call:
this.setState({
name: 'Sean'
});
Will that achieve what you're aiming for?
For larger, more complex data stores, I would use something like Redux. But that's much more advanced.
The general rule with component state is to use it only to manage UI state of the component (e.g. active, timers, etc.)
Check out these references:
- https://facebook.github.io/react/docs/react-component.html#state
- https://facebook.github.io/react/docs/state-and-lifecycle.html
1
I only used that as an example, the object must be nested.. I probably should be using Redux but I am trying to understand React fundementals..
– JohnSnow
Apr 26 '17 at 16:07
2
Yeah, I would stay away from Redux for now. While you're learning the fundamentals, try to keep your data simple. That'll help you avoid odd cases that trip you up. 👍
– mccambridge
Apr 26 '17 at 16:39
add a comment |
The first case is indeed a syntax error.
Since I can't see the rest of your component, it's hard to see why you're nesting objects in your state here. It's not a good idea to nest objects in component state. Try setting your initial state to be:
this.state = {
name: 'jasper',
age: 28
}
That way, if you want to update the name, you can just call:
this.setState({
name: 'Sean'
});
Will that achieve what you're aiming for?
For larger, more complex data stores, I would use something like Redux. But that's much more advanced.
The general rule with component state is to use it only to manage UI state of the component (e.g. active, timers, etc.)
Check out these references:
- https://facebook.github.io/react/docs/react-component.html#state
- https://facebook.github.io/react/docs/state-and-lifecycle.html
The first case is indeed a syntax error.
Since I can't see the rest of your component, it's hard to see why you're nesting objects in your state here. It's not a good idea to nest objects in component state. Try setting your initial state to be:
this.state = {
name: 'jasper',
age: 28
}
That way, if you want to update the name, you can just call:
this.setState({
name: 'Sean'
});
Will that achieve what you're aiming for?
For larger, more complex data stores, I would use something like Redux. But that's much more advanced.
The general rule with component state is to use it only to manage UI state of the component (e.g. active, timers, etc.)
Check out these references:
- https://facebook.github.io/react/docs/react-component.html#state
- https://facebook.github.io/react/docs/state-and-lifecycle.html
answered Apr 26 '17 at 16:06
mccambridgemccambridge
764414
764414
1
I only used that as an example, the object must be nested.. I probably should be using Redux but I am trying to understand React fundementals..
– JohnSnow
Apr 26 '17 at 16:07
2
Yeah, I would stay away from Redux for now. While you're learning the fundamentals, try to keep your data simple. That'll help you avoid odd cases that trip you up. 👍
– mccambridge
Apr 26 '17 at 16:39
add a comment |
1
I only used that as an example, the object must be nested.. I probably should be using Redux but I am trying to understand React fundementals..
– JohnSnow
Apr 26 '17 at 16:07
2
Yeah, I would stay away from Redux for now. While you're learning the fundamentals, try to keep your data simple. That'll help you avoid odd cases that trip you up. 👍
– mccambridge
Apr 26 '17 at 16:39
1
1
I only used that as an example, the object must be nested.. I probably should be using Redux but I am trying to understand React fundementals..
– JohnSnow
Apr 26 '17 at 16:07
I only used that as an example, the object must be nested.. I probably should be using Redux but I am trying to understand React fundementals..
– JohnSnow
Apr 26 '17 at 16:07
2
2
Yeah, I would stay away from Redux for now. While you're learning the fundamentals, try to keep your data simple. That'll help you avoid odd cases that trip you up. 👍
– mccambridge
Apr 26 '17 at 16:39
Yeah, I would stay away from Redux for now. While you're learning the fundamentals, try to keep your data simple. That'll help you avoid odd cases that trip you up. 👍
– mccambridge
Apr 26 '17 at 16:39
add a comment |
try this,it should work fine
this.setState(Object.assign(this.state.jasper,{name:'someOtherName'}));
I've tried many other methods... but your snippet is rock! thanks man
– hendra1
Jan 23 at 13:14
Thank you very much for letting me know. I am happy that resolved your problem.
– Burak Kahraman
Jan 24 at 15:37
add a comment |
try this,it should work fine
this.setState(Object.assign(this.state.jasper,{name:'someOtherName'}));
I've tried many other methods... but your snippet is rock! thanks man
– hendra1
Jan 23 at 13:14
Thank you very much for letting me know. I am happy that resolved your problem.
– Burak Kahraman
Jan 24 at 15:37
add a comment |
try this,it should work fine
this.setState(Object.assign(this.state.jasper,{name:'someOtherName'}));
try this,it should work fine
this.setState(Object.assign(this.state.jasper,{name:'someOtherName'}));
answered Jan 1 at 12:40
Burak KahramanBurak Kahraman
213
213
I've tried many other methods... but your snippet is rock! thanks man
– hendra1
Jan 23 at 13:14
Thank you very much for letting me know. I am happy that resolved your problem.
– Burak Kahraman
Jan 24 at 15:37
add a comment |
I've tried many other methods... but your snippet is rock! thanks man
– hendra1
Jan 23 at 13:14
Thank you very much for letting me know. I am happy that resolved your problem.
– Burak Kahraman
Jan 24 at 15:37
I've tried many other methods... but your snippet is rock! thanks man
– hendra1
Jan 23 at 13:14
I've tried many other methods... but your snippet is rock! thanks man
– hendra1
Jan 23 at 13:14
Thank you very much for letting me know. I am happy that resolved your problem.
– Burak Kahraman
Jan 24 at 15:37
Thank you very much for letting me know. I am happy that resolved your problem.
– Burak Kahraman
Jan 24 at 15:37
add a comment |
Another option: define your variable out of the Jasper object and then just call a variable.
Spread operator: ES6
this.state = { jasper: { name: 'jasper', age: 28 } }
let foo = "something that needs to be saved into state"
this.setState(prevState => ({
jasper: {
...jasper.entity,
foo
}
})
1
I am not sure the downvoter(s) understood thatfoo
expands tofoo: foo
...
– Cory Silva
Dec 8 '18 at 16:55
add a comment |
Another option: define your variable out of the Jasper object and then just call a variable.
Spread operator: ES6
this.state = { jasper: { name: 'jasper', age: 28 } }
let foo = "something that needs to be saved into state"
this.setState(prevState => ({
jasper: {
...jasper.entity,
foo
}
})
1
I am not sure the downvoter(s) understood thatfoo
expands tofoo: foo
...
– Cory Silva
Dec 8 '18 at 16:55
add a comment |
Another option: define your variable out of the Jasper object and then just call a variable.
Spread operator: ES6
this.state = { jasper: { name: 'jasper', age: 28 } }
let foo = "something that needs to be saved into state"
this.setState(prevState => ({
jasper: {
...jasper.entity,
foo
}
})
Another option: define your variable out of the Jasper object and then just call a variable.
Spread operator: ES6
this.state = { jasper: { name: 'jasper', age: 28 } }
let foo = "something that needs to be saved into state"
this.setState(prevState => ({
jasper: {
...jasper.entity,
foo
}
})
edited Jun 15 '18 at 10:54
J. Steen
10.3k124961
10.3k124961
answered Feb 20 '18 at 2:28
Luis MartinsLuis Martins
637510
637510
1
I am not sure the downvoter(s) understood thatfoo
expands tofoo: foo
...
– Cory Silva
Dec 8 '18 at 16:55
add a comment |
1
I am not sure the downvoter(s) understood thatfoo
expands tofoo: foo
...
– Cory Silva
Dec 8 '18 at 16:55
1
1
I am not sure the downvoter(s) understood that
foo
expands to foo: foo
...– Cory Silva
Dec 8 '18 at 16:55
I am not sure the downvoter(s) understood that
foo
expands to foo: foo
...– Cory Silva
Dec 8 '18 at 16:55
add a comment |
Also, following Alberto Piras solution, if you don't want to copy all the "state" object:
handleChange(el) {
let inputName = el.target.name;
let inputValue = el.target.value;
let jasperCopy = Object.assign({}, this.state.jasper);
jasperCopy[inputName].name = inputValue;
this.setState({jasper: jasperCopy});
}
add a comment |
Also, following Alberto Piras solution, if you don't want to copy all the "state" object:
handleChange(el) {
let inputName = el.target.name;
let inputValue = el.target.value;
let jasperCopy = Object.assign({}, this.state.jasper);
jasperCopy[inputName].name = inputValue;
this.setState({jasper: jasperCopy});
}
add a comment |
Also, following Alberto Piras solution, if you don't want to copy all the "state" object:
handleChange(el) {
let inputName = el.target.name;
let inputValue = el.target.value;
let jasperCopy = Object.assign({}, this.state.jasper);
jasperCopy[inputName].name = inputValue;
this.setState({jasper: jasperCopy});
}
Also, following Alberto Piras solution, if you don't want to copy all the "state" object:
handleChange(el) {
let inputName = el.target.name;
let inputValue = el.target.value;
let jasperCopy = Object.assign({}, this.state.jasper);
jasperCopy[inputName].name = inputValue;
this.setState({jasper: jasperCopy});
}
answered Aug 13 '18 at 9:17
Marc LaQuayMarc LaQuay
15016
15016
add a comment |
add a comment |
You can try with this:
(Note: name of input tag === field of object)
<input name="myField" type="text"
value={this.state.myObject.myField}
onChange={this.handleChangeInpForm}></input>
-----------------------------------------------------------
handleChangeInpForm = (e) => {
let newObject = this.state.myObject;
newObject[e.target.name] = e.target.value;
this.setState({
myObject: newObject
})
}
Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer
– Elletlar
Jan 28 at 12:51
add a comment |
You can try with this:
(Note: name of input tag === field of object)
<input name="myField" type="text"
value={this.state.myObject.myField}
onChange={this.handleChangeInpForm}></input>
-----------------------------------------------------------
handleChangeInpForm = (e) => {
let newObject = this.state.myObject;
newObject[e.target.name] = e.target.value;
this.setState({
myObject: newObject
})
}
Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer
– Elletlar
Jan 28 at 12:51
add a comment |
You can try with this:
(Note: name of input tag === field of object)
<input name="myField" type="text"
value={this.state.myObject.myField}
onChange={this.handleChangeInpForm}></input>
-----------------------------------------------------------
handleChangeInpForm = (e) => {
let newObject = this.state.myObject;
newObject[e.target.name] = e.target.value;
this.setState({
myObject: newObject
})
}
You can try with this:
(Note: name of input tag === field of object)
<input name="myField" type="text"
value={this.state.myObject.myField}
onChange={this.handleChangeInpForm}></input>
-----------------------------------------------------------
handleChangeInpForm = (e) => {
let newObject = this.state.myObject;
newObject[e.target.name] = e.target.value;
this.setState({
myObject: newObject
})
}
edited Jan 30 at 3:47
answered Jan 28 at 12:31
Xuanduong NgoXuanduong Ngo
11
11
Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer
– Elletlar
Jan 28 at 12:51
add a comment |
Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer
– Elletlar
Jan 28 at 12:51
Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer
– Elletlar
Jan 28 at 12:51
Welcome to Stack Overflow. While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. How to Answer
– Elletlar
Jan 28 at 12:51
add a comment |
Simple and dynamic way.
This will do the job, but you need to set all the ids to the parent so the parent will point to the name of the object, being id = "jasper" and name the name of the input element = property inside of the object jasper.
handleChangeObj = ({target: { id , name , value}}) => this.setState({ [id]: { ...this.state[id] , [name]: value } });
add a comment |
Simple and dynamic way.
This will do the job, but you need to set all the ids to the parent so the parent will point to the name of the object, being id = "jasper" and name the name of the input element = property inside of the object jasper.
handleChangeObj = ({target: { id , name , value}}) => this.setState({ [id]: { ...this.state[id] , [name]: value } });
add a comment |
Simple and dynamic way.
This will do the job, but you need to set all the ids to the parent so the parent will point to the name of the object, being id = "jasper" and name the name of the input element = property inside of the object jasper.
handleChangeObj = ({target: { id , name , value}}) => this.setState({ [id]: { ...this.state[id] , [name]: value } });
Simple and dynamic way.
This will do the job, but you need to set all the ids to the parent so the parent will point to the name of the object, being id = "jasper" and name the name of the input element = property inside of the object jasper.
handleChangeObj = ({target: { id , name , value}}) => this.setState({ [id]: { ...this.state[id] , [name]: value } });
edited Mar 30 at 22:44
answered Mar 30 at 22:39
Alejandro Sánchez DuránAlejandro Sánchez Durán
214
214
add a comment |
add a comment |
You can try with this:
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState.name = 'someOtherName';
return {jasper: prevState}
})
or for other property:
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState.age = 'someOtherAge';
return {jasper: prevState}
})
Or you can use handleChage function:
handleChage(event) {
const {name, value} = event.target;
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState[name] = value;
return {jasper: prevState}
})
}
and HTML code:
<input
type={"text"}
name={"name"}
value={this.state.jasper.name}
onChange={this.handleChange}
/>
<br/>
<input
type={"text"}
name={"age"}
value={this.state.jasper.age}
onChange={this.handleChange}
/>
add a comment |
You can try with this:
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState.name = 'someOtherName';
return {jasper: prevState}
})
or for other property:
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState.age = 'someOtherAge';
return {jasper: prevState}
})
Or you can use handleChage function:
handleChage(event) {
const {name, value} = event.target;
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState[name] = value;
return {jasper: prevState}
})
}
and HTML code:
<input
type={"text"}
name={"name"}
value={this.state.jasper.name}
onChange={this.handleChange}
/>
<br/>
<input
type={"text"}
name={"age"}
value={this.state.jasper.age}
onChange={this.handleChange}
/>
add a comment |
You can try with this:
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState.name = 'someOtherName';
return {jasper: prevState}
})
or for other property:
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState.age = 'someOtherAge';
return {jasper: prevState}
})
Or you can use handleChage function:
handleChage(event) {
const {name, value} = event.target;
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState[name] = value;
return {jasper: prevState}
})
}
and HTML code:
<input
type={"text"}
name={"name"}
value={this.state.jasper.name}
onChange={this.handleChange}
/>
<br/>
<input
type={"text"}
name={"age"}
value={this.state.jasper.age}
onChange={this.handleChange}
/>
You can try with this:
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState.name = 'someOtherName';
return {jasper: prevState}
})
or for other property:
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState.age = 'someOtherAge';
return {jasper: prevState}
})
Or you can use handleChage function:
handleChage(event) {
const {name, value} = event.target;
this.setState(prevState => {
prevState = JSON.parse(JSON.stringify(this.state.jasper));
prevState[name] = value;
return {jasper: prevState}
})
}
and HTML code:
<input
type={"text"}
name={"name"}
value={this.state.jasper.name}
onChange={this.handleChange}
/>
<br/>
<input
type={"text"}
name={"age"}
value={this.state.jasper.age}
onChange={this.handleChange}
/>
edited Jan 3 at 13:00
answered Jan 3 at 12:46
Nemanja StojanovicNemanja Stojanovic
65
65
add a comment |
add a comment |
protected by Community♦ Mar 14 at 18:31
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
3
second code would have worked however you would have lost the
age
property insidejasper
.– giorgim
Jul 10 '18 at 8:14