Reputation: 1499
I'm trying to create a function that allows me to add items to an array in the local state. I could create several functions that cater to each array in the state, but I feel like I should be able to only need one function that does this. The way I'm doing it isn't working. I probably need to take a step back and reconsider but I was hoping to find some way to make this work.
Thanks!
this.state = {
category1: [],
category2: []
}
addItem(category, type){
this.setState({
category: [...this.state.category, type]
})
}
listsOfItems.types.map((type, i) => (
<ListItem
onPress={ () => this.addItem(category1, type)}
/>
))
listOfOtherItems.types.map((type, i) => {
<ListItem
onPress={ () => this.addItem(category2, type)}
/>
})
Upvotes: 1
Views: 38
Reputation: 112787
I don't think repetition in this case is that bad, but if you really want to generalize it, you could use a computed property name:
this.state = {
category1: [],
category2: []
}
addItem(category, type){
this.setState({
[category]: [...this.state[category], type]
})
}
listsOfItems.types.map((type, i) => (
<ListItem
onPress={ () => this.addItem('category1', type)}
/>
))
listOfOtherItems.types.map((type, i) => {
<ListItem
onPress={ () => this.addItem('category2', type)}
/>
})
Upvotes: 1