I can’t add the product to favorite page and get the above error.
I’m using React-Native with context hook to add the product to cart and favorite pages. The problem is all actions in reducer hook are working except add to favorite action is not working.
Context Code
const initialState = {
products: ProductData, // productData is dummy data where i place all products with details
cart: [],
FavoritesList: [],
};
const reducer = (state = initialState, action) => {
switch(action.type) {
case 'ADD_PRODUCT_TO_FAVORITE':
const product = action.payload;
const index = state.products.findIndex((item)=> item?.id === product?.id)
if (index >= 0) {
state.splice(index, 1);
} else {
state.push(product)
}
return [...state,];
case 'CLEAR':
return {cart :[]}
default:
throw new Error(`unknow action.${action.type}`)
}
}
favorite screen code
const Faviroute = () => {
const { FavoritesList } = useCart();
return (
<View
style={{
// flex:1,
}}
>
{(FavoritesList.length === 0) ?
<View>
<Text>Get your favourite Coffee easily</Text>
</View>
: <View>
{/*Card Container*/}
<ScrollView>
<View>
{FavoritesList.map((item, index) => (
<View key={index}>
<Text>{`Product Name: ${item.name}`}</Text>
<Text>{`Size: ${item.size}`}</Text>
<Text>{`Quantity: ${item.qty}`}</Text>
<Text>{`Price: ${item.price}`}</Text>
</View>
))}
</View>
</ScrollView>
</View>
}
</View>
)
}
2
Answers
Array
splice
andpush
methods mutate the existing array reference. Create shallow copies then overwrite. In this case if you would like to remove an element then filter the current state, and when adding an element concatenate. Make sure you are updating and returning the correct state properties.Example:
Suggestion
Instead of double-storing the product data, the "favorited" products should store just the product id. You can get back the complete favorites array derived from the products array filtered by products with a favorited id.
Example:
Can you try below mentioned code.