Ok so this are my buttons where I add and delete from cart in ProductScreen :
<TouchableOpacity onPress={()=>{this.addToCart()}}>
<Text>add to cart</Text>
</TouchableOpacity>
<TouchableOpacity onPress={()=>{this.props.updateCart({'numberOfProducts':0,'products':[]})}}>
<Text>Erase cart</Text>
<TouchableOpacity>
The addToCart function :
addToCart = () =>{
let currentCartProducts = this.props.cart;
currentCartProducts.numberOfProducts++;
this.setState({
currentProductToAdd:Object.assign(
this.state.currentProductToAdd,
{
'toalPriceOfProductWithExtras': this.props.navigation.getParam('price') * this.state.value,
'piecesOfProduct': this.state.value,
}
)
})
currentCartProducts.products.push(this.state.currentProductToAdd);
this.props.updateCart(currentCartProducts);
}
The CartReducer
const INITIAL_STATE = {'numberOfProducts':0,'products':[]};
export default (state = INITIAL_STATE, action) => {
switch(action.type) {
case 'update':
return action.payload;
default:
return state;
}
};
The CartAction
export const updateCart = (val) => {
return{
type: 'update',
payload: val
};
};
And the CartScreen componentWillReceiveProps where I want to render the products that are in cart. The redux works good , and I have all the data stored correctly but they don't render !
componentWillReceiveProps(nextProps) {
console.log('I m in componentWillReceiveProps')
if (this.props.cart !== nextProps.cart) {
console.log('OLD CART')
console.log(this.props.cart)
console.log('NEW CART')
console.log(nextProps.cart)
}
}
When I press add it doesn't work , but when I press delete it works !
After one add and one delete :
I m in componentWillReceiveProps
OLD CART
Object {
"numberOfProducts": 1,
"products": Array [
Object {
"extras": undefined,
"piecesOfProduct": 1,
"productName": "Chips",
"productPrice": 0,
"restaurantAddres": "Tay House 300 Bath St",
"restaurantName": "time2dine - Spaces",
"toalPriceOfProductWithExtras": 0,
},
],
}
NEW CART
Object {
"numberOfProducts": 0,
"products": Array [],
}
After another delete press:
I m in componentWillReceiveProps
OLD CART
Object {
"numberOfProducts": 0,
"products": Array [],
}
NEW CART
Object {
"numberOfProducts": 0,
"products": Array [],
}
It's strange because at the second press on delete the cart props are the same... but when I add and the props change doesn't show anything.
Thank you !
I think you're not properly updating your store.
case 'update':`
return {...state, ...action.payload};
Update this in cartReducer.js
. You should remember to use the spread operator otherwise the state will be the same anytime you update the store which will cause the componentWillReceiveProps
not work as expected. Hope it helps!!.. Happy Coding!!