I have created a like function that changes color only for a single item, and that item according to its id is liked, however when I like the first item, the id of the same is passed but all the icons are also turning to red, how do I undo that?
my like function is as follows:
onButtonPress = async(item) => {
console.log(item)
console.log(this.state.buttonColor,'hello')
if(this.state.buttonColor='white'){
try {
const response = await fetch("some url"+item._id);
const resJson = await response.text();
this.setState({
buttonColor:'red',
}, console.log(resJson),
console.log(this.state.buttonColor,'hi'));
}
catch (error) {
console.error(error);
}
}
};
I have called this function inside a flatlist as an icon, I will share the snippet of the icon below:
<TouchableOpacity
onPress= {() => this.onButtonPress(item)}
style={{
alignItems: 'center',
borderRadius: 60,
padding: 10,
}}>
<Icon
name="heart"
size={30}
color={this.state.buttonColor}
/>
</TouchableOpacity>
Do, tell me if you require anything else, and let me know how to do it?
You need store in state element's id, which have active state (red color).
onButtonPress = async(item) => {
if(!this.state.likedItemIds.includes(item._id)){
try {
const response = await fetch("some url"+item._id);
const resJson = await response.text();
this.setState(prevState => ({
likedItemIds: [...prevState.likedItemIds, item._id]
}))
}
catch (error) {
console.error(error);
}
}
};
<TouchableOpacity
onPress= {() => this.onButtonPress(item)}
style={{
alignItems: 'center',
borderRadius: 60,
padding: 10,
}}>
<Icon
name="heart"
size={30}
color={state.likedItemIds.includes(item._id) ? "red" : "white"}
/>
</TouchableOpacity>