Reputation: 329
I am using a for loop to loop through categories from an API which works as expected:
renderFilter=()=> {
const items = [];
for (item of this.state.newsCats) {
items.push(
<TouchableOpacity key={item.module_cat_id} onPress={()=>this.FilterRequest(item.module_cat_id)}><Text style={styles.filterCat}>{item.module_cat} {item.module_cat_id}</Text></TouchableOpacity>
);
}
return items;
}
FilterRequest fires correctly onPress but it always returns the last module_cat_id in the loop rather than the id of the category selected:
FilterRequest = (module_cat_id) => {
console.log(module_cat_id);
this.setState({
news_cat_id: module_cat_id,
}, () =>{
this.NewsRequest();
this.setModalVisible(!this.state.modalVisible)
});
}
How can I get the correct item.module_cat_id
into FilterRequest?
Both code snippets are in the same js file.
Upvotes: 1
Views: 624
Reputation: 6325
It looks like you are missing the declaration of the item
variable in the for of loop inside renderFilter
method:
renderFilter = () => {
const items = [];
for (let item of this.state.newsCats) {
items.push(
<TouchableOpacity key={item.module_cat_id} onPress={()=>this.FilterRequest(item.module_cat_id)}><Text style={styles.filterCat}>{item.module_cat} {item.module_cat_id}</Text></TouchableOpacity>
);
}
return items;
}
Upvotes: 1