Skip to main content

8.18 Removing Igredients Safely

BurgerBuilder.js

BurgerBuilder.js
import React, { Component, Fragment } from "react";
import BuildControls from "../components/Burger/BuildControls/BuildControls";
import Burger from "../components/Burger/Burger";

const INGREDIENT_PRICES = {
salad: 0.5,
cheese: 0.4,
meat: 1.3,
bacon: 0.7,
};

class BurgerBuilder extends Component {
// constructor(props) {
// super(props);
// this.state = {...}
// }
state = {
ingredients: {
salad: 0,
bacon: 0,
cheese: 0,
meat: 0,
},
totalPrice: 4,
};

addIngredientHandler = (type) => {
const oldCount = this.state.ingredients[type];
const updateCount = oldCount + 1;
const updatedIngredients = {
...this.state.ingredients,
};
updatedIngredients[type] = updateCount;
const priceAddition = INGREDIENT_PRICES[type];
const oldPrice = this.state.totalPrice;
const newPrice = oldPrice + priceAddition;
this.setState({ totalPrice: newPrice, ingredients: updatedIngredients });
};

removeIngredientHandler = (type) => {
const oldCount = this.state.ingredients[type];
if (oldCount <= 0) {
return;
}
const updateCount = oldCount - 1;
const updatedIngredients = {
...this.state.ingredients,
};
updatedIngredients[type] = updateCount;
const priceDeduction = INGREDIENT_PRICES[type];
const oldPrice = this.state.totalPrice;
const newPrice = oldPrice - priceDeduction;
this.setState({ totalPrice: newPrice, ingredients: updatedIngredients });
};

render() {
const disabledInfo = {
...this.state.ingredients,
};

for (let key in disabledInfo) {
disabledInfo[key] = disabledInfo[key] <= 0;
}

return (
<Fragment>
<Burger ingredients={this.state.ingredients} />
<BuildControls
ingredientAdded={this.addIngredientHandler}
ingredientRemoved={this.removeIngredientHandler}
disabled={disabledInfo}
/>
</Fragment>
);
}
}
export default BurgerBuilder;

BuildControls.js

BuildControls.js
import React from "react";
import BuildControl from "./BuildControl/BuildControl";
import classes from "./BuildControls.module.css";
const controls = [
{ label: "Salad", type: "salad" },
{ label: "Bacon", type: "bacon" },
{ label: "Cheese", type: "cheese" },
{ label: "Meat", type: "meat" },
];

const buildControls = (props) => (
<div className={classes.BuildControls}>
{controls.map((ctrl) => (
<BuildControl
key={ctrl.label}
label={ctrl.label}
added={() => props.ingredientAdded(ctrl.type)}
removed={() => props.ingredientRemoved(ctrl.type)}
disabled={props.disabled[ctrl.type]}
/>
))}
</div>
);

export default buildControls;

BuildControl.js

BuildControl.js
import React from "react";
import classes from "./BuildControl.module.css";

const buildControl = (props) => (
<div className={classes.BuildControl}>
<div className={classes.Label}>{props.label}</div>
<button
className={classes.Less}
onClick={props.removed}
disabled={props.disabled}
>
Less
</button>
<button className={classes.More} onClick={props.added}>
More
</button>
</div>
);

export default buildControl;