I have a nested object as a state and I have a form in a ponent. I was thinking of updating the state every time the user enter something in the form and to avoid creating many functions for each input I was thinking of creating a single function using switch.
- Is creating a single function with switch a good idea?
- How can I update a single nested element of the object?
I have tried with the following code but it doesn't work:
class App extends Component {
constructor(props) {
super(props)
this.state = {
minutes: null,
interests: {
business: false,
code: false,
design: false
},
errors: []
}
}
updatePreferences = (preferenceName, enteredValue) => {
switch (preferenceName) {
case preferenceName === "minutes":
this.setState({minutes: enteredValue})
return
case preferenceName === "business":
this.setState({interests.business: !this.state.interests.business})
return
case default:
return
}
}
}
I have a nested object as a state and I have a form in a ponent. I was thinking of updating the state every time the user enter something in the form and to avoid creating many functions for each input I was thinking of creating a single function using switch.
- Is creating a single function with switch a good idea?
- How can I update a single nested element of the object?
I have tried with the following code but it doesn't work:
class App extends Component {
constructor(props) {
super(props)
this.state = {
minutes: null,
interests: {
business: false,
code: false,
design: false
},
errors: []
}
}
updatePreferences = (preferenceName, enteredValue) => {
switch (preferenceName) {
case preferenceName === "minutes":
this.setState({minutes: enteredValue})
return
case preferenceName === "business":
this.setState({interests.business: !this.state.interests.business})
return
case default:
return
}
}
}
Share
Improve this question
asked May 22, 2017 at 16:38
ocramocram
1,4446 gold badges21 silver badges38 bronze badges
1 Answer
Reset to default 8Of course you can use switch
, Nothing wrong AFAIK.
And to update nested objects with setState
. See the example
updatePreferences = (preferenceName, enteredValue) => {
switch (preferenceName) {
case preferenceName === "minutes":
this.setState({minutes: enteredValue});
return
case preferenceName === "business":
this.setState({...this.state, interests: {
...this.state.interests,
business: !this.state.interests.business
}});
return
default:
return
}
}