What I want is to increment the count for each individual item but when I'm trying to do that it changes for every element rendered. I'm getting data from API and fetching it to redux store and mapping over the array. But could not differ each element.
return (
<View style={styles.Container}>
{movies ? (
movies.map((data,i) => {
const IMAGE_URL = data.image;
return (
<Card key={i}>
<View style={styles.Content}>
<Card.Cover style={styles.image} source={{ uri: IMAGE_URL }} />
<ScrollView style={styles.ProductDetails}>
<Text
style={{
fontSize: 15,
fontWeight: "bold",
paddingBottom: 10,
}}
>
{data.title}
</Text>
<Paragraph>{data.description}</Paragraph>
</ScrollView>
</View>
<View style={styles.BottomButtonView}>
<View style={{ flexDirection: "row", alignItems: "center" }}>
<TouchableOpacity
key={i}
style={styles.ButtonContainer}
onPress={() => setCount(count+1)}
>
<Text style={{ color: "white" }}>+</Text>
</TouchableOpacity>
<Text style={{ padding: 10 }}>{count}</Text>
<TouchableOpacity
style={styles.ButtonContainer}
onPress={() => console.log('dec')}
>
<Text style={{ color: "white" }}>-</Text>
</TouchableOpacity>
</View>
<TouchableOpacity
onPress={() => console.log("Added to Cart")}
style={styles.AddToCart}
>
<Text style={{ color: "white" }}>${data.price}</Text>
</TouchableOpacity>
</View>
</Card>
);
})
) : (
<Text>Getting Data....</Text>
)}
</View>
);
}
Updating an Item in an Array :
function updateObjectInArray(array, action) {
return array.map((item, index) => {
if (index !== action.index) {
// This isn't the item we care about - keep it as-is
return item
}
// Otherwise, this is the one we want - return an updated value
return {
...item,
...action.item
}
})
}
for Example :
const changePrice = (itemArray, item) => {
return itemArray.map(reduxItem => {
if(reduxItem.id === item.id){
reduxItem.price = reduxItem.price + reduxItem.price
}
return reduxItem
});
};