Here, in this picture, I have 3 items with description, rate, quantity and amount. Currently, I am storing only description, rate and quantity in redux. Amount is just for displaying. I want to get the sub total of all the items.
items.map((item, index) => {
return{
<Input
placeholder="Description"
value={item && item.description}
onChange={event => {
setValuesToRedux(
`items[${index}].description`,
event.target.value
);
}}
/>
<Input
placeholder="0.00"
value={item && item.rate}
onChange={event => {
setValuesToRedux(
`items[${index}].rate`,
event.target.value
);
}}
/>
<Input
placeholder="0"
value={item && item.quantity}
onChange={event => {
setValuesToRedux(
`items[${index}].quantity`,
event.target.value
);
}}
/>
<p>{item && item.rate && item.quanity && item.rate * item.quantity}</p>
}
}))
After getting rate and quantity for all the items, I want to calculate subtotal, I am not getting how to do because we are storing everyting on onChange function.
In redux, I am storing items as:
items: [ {description: "item1", rate: 200, quantity: 1},
{description: "item2", rate: 300, quantity: 1},
{description: "item3", rate: 400, quantity: 1}
]
Thanks in Advance!!
When you are displaying the price at the end of the row, provide a class to that field.
After that, just get the values of that class and add them in the onChange
function and display at the end.
Let me know how it goes or anyone has a better idea.
I have two options
initial state:
const state = {
items: [],
subtotal: 0,
}
//...
switch(type) {
case ADD_ITEM:{
return {
...state,
items: [...state.items, payload],
subtotal: state.subtotal + (payload.rate * payload.quantity)
}
}
}
Render subtotal
in the UI, it changes as items change
I am using reduce()
//..
render() {
const subtotal = items.reduce((total, item) => total + item.rate * item.quantity, 0);
return() {
//Items
<p>Subtotal: {subtotal}<p>
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.