I have data in an array of objects:
const data = [
{
id: 1,
category: "tables",
name: "N/A",
price: 0,
},
{
id: 2,
category: "tables",
name: "Table 1",
price: 220,
},
{
id: 3,
category: "tables",
name: "Table 2",
price: 420,
},
{
id: 4,
category: "tables",
name: "Table 3",
price: 515,
},
{
id: 5,
category: "tables",
name: "Table 4",
price: 495,
},
{
id: 6,
category: "tables",
name: "Table 5",
price: 210,
},
{
id: 7,
category: "chairs",
name: "N/A",
price: 0,
},
{
id: 8,
category: "chairs",
name: "Chair 1",
price: 75,
},
{
id: 9,
category: "chairs",
name: "Chair 2",
price: 150,
},
{
id: 10,
category: "desks",
name: "Desk 1",
price: 75,
},
{
id: 11,
category: "desks",
name: "Desk 2",
price: 130,
},
{
id: 12,
category: "desks",
name: "Desk 3",
price: 215,
},
{
id: 13,
category: "desks",
name: "Desk 4",
price: 275,
},
{
id: 14,
category: "lighting",
name: "Lighting 1",
price: 105,
},
{
id: 15,
category: "lighting",
name: "Lighting 2",
price: 150,
},
];
export default data;
I have a reducer which updates the state depending on which items the user selects on the page (via radios, checkboxes and quantity inputs). Here's what the initial state looks like. The nested keys correspond to the ids in data
and the values are the quantities, e.g. there are two desks currently selected (with ids 10 and 12, and 1 quantity of each). Lighting has x2 of id 14 and id 15 has its quantity set to zero as this is output on the page as the initial value in a quantity input.
const [reducerState, dispatch] = useReducer(reducer, {
tables: {
1: 1,
},
chairs: {
7: 1,
},
desks: {
10: 1,
12: 1,
},
lighting: {
14: 2,
15: 0,
},
});
What I need to do is calculate a total price based on the ids and quantities in state. In this example it should be £500. How can I generate this and output it on the page in the JSX?
Any help appreciated, thanks.
CodePudding user response:
Here's a working example:
You have to create a reducer function which goes through every selected option, finds that id in the data and then adds the count*price to the sum so far.
https://codesandbox.io/s/keen-sammet-b5m3y9?file=/src/App.js
CodePudding user response:
I do not know what your reducer switch does, but the logic to check and eventually add the price could be:
const totalPriceForType=(data,initState) => data.map(item=>
initState.map(id=>
item.id===id && item.price =item.price))