D
D
DeniSidorenko2020-12-15 10:46:52
React
DeniSidorenko, 2020-12-15 10:46:52

Is it correct to implement such logic on Redux or what advice could be better?

There is a shopping cart, adding and storing made through Redux. There are different action.types, add to cart, remove from cart, add unit, remove unit, etc.
It was also necessary to calculate the final price during the update. I thought for each action.type to add a map loop and go through all the prices, but this works with a delay of 1 click, the state is updated. I did it in the following way, but it seems to me not quite correct, although it works

fine

componentDidUpdate(prevProps, prevState, snapshot) {
    const products = this.props.cart
    let totalPrice = 0
    products.map(item =>{
      totalPrice += item.priceGroup
    })
    this.props.updatePrice(totalPrice)
  }


export function updatePrice(totalPrice){
  return{
    type: UPDATE_PRICE,
    totalPrice
  }
}


ase UPDATE_PRICE:
      return {
        ...state,
        totalPrice: action.totalPrice
      }


As I said, everything works) but with Update_PRICE, componentDidUpdate fires again, i.e. it works 2 times for each iteration (first for quantity changes, and then again for the fact that the price has been updated and the state has been updated)
What could be more correct solutions
Structure such
Z4NxO.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Shcherbakov, 2020-12-15
@Simply1993

Create a simple selector that will take all items from cart and calculate the total price.
This selector can be used in the desired component, where it needs to be drawn.
Use the library - reselect. It is not necessary to store the amount in the store.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question