Skip to content

Commit

Permalink
Updated app to work with Redux (Basic)
Browse files Browse the repository at this point in the history
  • Loading branch information
RodrigoTomeES committed Dec 12, 2019
1 parent 610ce55 commit 52ad453
Show file tree
Hide file tree
Showing 6 changed files with 124 additions and 133 deletions.
143 changes: 45 additions & 98 deletions src/containers/BurgerBuilder/BurgerBuilder.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, {Component} from 'react';
import axios from '../../axios-orders';
import {connect} from 'react-redux';

import Aux from '../../hoc/Auxiliary/Auxiliary';
import Burger from '../../components/Burger/Burger';
Expand All @@ -8,42 +9,34 @@ import Modal from '../../components/UI/Modal/Modal';
import OrderSummary from '../../components/Burger/OrderSummary/OrderSummary';
import Spinner from '../../components/UI/Spinner/Spinner';
import withErrorHandler from '../../hoc/withErrorHandler/withErrorHandler';

const INGREDIENT_PRICES = {
salad: 0.5,
cheese: 0.4,
bacon: 0.7,
meat: 1.3
}
import * as actionTypes from '../../store/actions';

class BurguerBuilder extends Component {
state = {
ingredients: null,
totalPrice: 5,
purchasable: false,
purchasing: false,
error: false
}

componentDidMount() {
axios.get('/ingredients.json')
.then(response => {
const ingredients = response.data;
let price = this.state.totalPrice;
for (let ingredient in ingredients) {
price += INGREDIENT_PRICES[ingredient] * ingredients[ingredient];
}
this.setState({
ingredients: ingredients,
totalPrice: price
});
})
.catch(error => {
this.setState({error: true});
});
// axios.get('/ingredients.json')
// .then(response => {
// const ingredients = response.data;
// let price = this.props.price;
// for (let ingredient in ingredients) {
// price += INGREDIENT_PRICES[ingredient] * ingredients[ingredient];
// }
// this.setState({
// ingredients: ingredients,
// totalPrice: price
// });
// })
// .catch(error => {
// this.setState({error: true});
// });
}

updatePurchaseState = (ingredients) => {
isPurchasable = () => {
const ingredients = this.props.ings;
const sum = Object.keys(ingredients)
.map(igkey => {
return ingredients[igkey];
Expand All @@ -52,57 +45,7 @@ class BurguerBuilder extends Component {
return sum + el;
}, 0);

this.setState({purchasable: sum > 0});
}

addIngredientHandler = (type) => {
// Updating ingredients
const oldCount = this.state.ingredients[type];
const updateCount = oldCount + 1;
const updatedIngredients = {
...this.state.ingredients
}
updatedIngredients[type] = updateCount;

// Updating pricing
const oldPrice = this.state.totalPrice;
const priceAddition = INGREDIENT_PRICES[type];
const newPrice = oldPrice + priceAddition;

// Updating state
this.setState({
ingredients: updatedIngredients,
totalPrice: newPrice,
});

// Updating purchasable
this.updatePurchaseState(updatedIngredients);
}

removeIngredientHandler = (type) => {
// Updating ingredients
const oldCount = this.state.ingredients[type];
// You can't have negative ingredients
if (oldCount <= 0) return;
const updateCount = oldCount - 1;
const updatedIngredients = {
...this.state.ingredients
}
updatedIngredients[type] = updateCount;

// Updating pricing
const oldPrice = this.state.totalPrice;
const priceDeduction = INGREDIENT_PRICES[type];
const newPrice = oldPrice - priceDeduction;

// Updating state
this.setState({
ingredients: updatedIngredients,
totalPrice: newPrice,
});

// Updating purchasable
this.updatePurchaseState(updatedIngredients);
return sum > 0;
}

purchaseHandler = () => {
Expand All @@ -114,48 +57,38 @@ class BurguerBuilder extends Component {
}

purchaseContinuedHandler = () => {
const queryParams = [];
for (let ingredient in this.state.ingredients) {
queryParams.push(encodeURIComponent(ingredient) + '=' + encodeURIComponent(this.state.ingredients[ingredient]));
}
queryParams.push('price=' + this.state.totalPrice);
const queryString = queryParams.join('&');

this.props.history.push({
pathname: '/checkout',
search: queryString
});
this.props.history.push('/checkout');
}

render() {
const disableInfo = {
...this.state.ingredients
...this.props.ings
}
for (let key in disableInfo) {
disableInfo[key] = disableInfo[key] <= 0;
}
let orderSummary = null;
let burger = this.state.error ? <p style={{textAlign: 'center'}}>Ingredients can't be loaded!</p> : <Spinner />;
if (this.state.ingredients) {
if (this.props.ings) {
burger = (
<Aux>
<Burger ingredients={this.state.ingredients} />
<Burger ingredients={this.props.ings} />
<BuildControls
ingredientAdded={this.addIngredientHandler}
ingredientRemoved={this.removeIngredientHandler}
ingredientAdded={this.props.onIngredientAdded}
ingredientRemoved={this.props.onIngredientRemoved}
disabled={disableInfo}
price={this.state.totalPrice}
purchasable={this.state.purchasable}
price={this.props.price}
purchasable={this.isPurchasable()}
ordered={this.purchaseHandler}
/>
</Aux>
);

orderSummary = <OrderSummary
ingredients={this.state.ingredients}
ingredients={this.props.ings}
purchaseCancelled={this.purchaseCancelHandler}
purchaseContinued={this.purchaseContinuedHandler}
price={this.state.totalPrice}
price={this.props.price}
/>;
}
return (
Expand All @@ -169,4 +102,18 @@ class BurguerBuilder extends Component {
}
}

export default withErrorHandler(BurguerBuilder, axios);
const mapStateToProps = state => {
return {
ings: state.ingredients,
price: state.totalPrice
};
};

const mapDispatchToProps = dispatch => {
return {
onIngredientAdded: (ingName) => dispatch({type: actionTypes.ADD_INGREDIENT, ingredientName: ingName}),
onIngredientRemoved: (ingName) => dispatch({type: actionTypes.REMOVE_INGREDIENT, ingredientName: ingName}),
};
};

export default connect(mapStateToProps, mapDispatchToProps)(withErrorHandler(BurguerBuilder, axios));
40 changes: 10 additions & 30 deletions src/containers/Checkout/Checkout.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,11 @@
import React, {Component} from 'react';
import {Route} from 'react-router-dom';
import {connect} from 'react-redux';

import CheckoutSmmary from '../../components/Order/CheckoutSummary/CheckoutSummary';
import ContactData from './ContactData/ContactData';

class Checkout extends Component {
state = {
ingredients: '',
totalPrice: 0
}

componentDidMount() {
const query = new URLSearchParams(this.props.location.search);
const ingredients = {};
let price = 0;
for (let param of query.entries()) {
if (param[0] === 'price') {
price = param[1]
} else {
ingredients[param[0]] = +param[1];
}
}

this.setState({
ingredients: ingredients,
totalPrice: price
});
}

checkoutCancelledHandler = () => {
this.props.history.goBack();
}
Expand All @@ -40,21 +18,23 @@ class Checkout extends Component {
return(
<div>
<CheckoutSmmary
ingredients={this.state.ingredients}
ingredients={this.props.ings}
checkoutCancelled={this.checkoutCancelledHandler}
checkoutContinued={this.checkoutContinuedHandler}
/>
<Route
path={this.props.match.path + '/contact-data'}
component={() => <ContactData
ingredients={this.state.ingredients}
price={this.state.totalPrice}
/>
}
component={ContactData}
/>
</div>
);
}
}

export default Checkout;
const mapStateToProps = state => {
return {
ings: state.ingredients
};
};

export default connect(mapStateToProps)(Checkout);
12 changes: 10 additions & 2 deletions src/containers/Checkout/ContactData/ContactData.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React, {Component} from 'react';
import { withRouter } from "react-router-dom";
import {connect} from 'react-redux';

import classes from './ContactData.module.css';
import Button from '../../../components/UI/Button/Button';
Expand Down Expand Up @@ -104,7 +105,7 @@ class ContactData extends Component {
formData[formElementIdentifier] = this.state.orderForm[formElementIdentifier].value;
}
const order = {
ingredients: this.props.ingredients,
ingredients: this.props.ings,
price: this.props.price,
orderData: formData
}
Expand Down Expand Up @@ -203,4 +204,11 @@ class ContactData extends Component {
}
}

export default withRouter(ContactData);
const mapStateToProps = state => {
return {
ings: state.ingredients,
price: state.totalPrice
};
};

export default connect(mapStateToProps)(withRouter(ContactData));
13 changes: 10 additions & 3 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import {Provider} from 'react-redux';
import {createStore} from 'redux';

import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import reducer from './store/reducer';

const store = createStore(reducer);

const app = (
<BrowserRouter basename='/burguer-builder/'>
<App />
</BrowserRouter>
<Provider store={store}>
<BrowserRouter basename='/burguer-builder/'>
<App />
</BrowserRouter>
</Provider>
);

ReactDOM.render(app, document.getElementById('root'));
Expand Down
2 changes: 2 additions & 0 deletions src/store/actions.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export const ADD_INGREDIENT = 'ADD_INGREDIENT';
export const REMOVE_INGREDIENT = 'REMOVE_INGREDIENT';
47 changes: 47 additions & 0 deletions src/store/reducer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import * as actionTypes from './actions';

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

const initialState = {
ingredients: {
salad: 0,
cheese: 0,
bacon: 0,
meat: 0
},
totalPrice: 5
};

const reducer = (state = initialState, action) => {
let updatedState = {
...state,
ingredients: {
...state.ingredients
}
};

const ingredient = action.ingredientName;

switch ( action.type ) {
case actionTypes.ADD_INGREDIENT:
updatedState.ingredients[ingredient] = state.ingredients[ingredient] + 1;
updatedState.totalPrice = state.totalPrice + INGREDIENT_PRICES[ingredient];
break;
case actionTypes.REMOVE_INGREDIENT:
updatedState.ingredients[ingredient] = state.ingredients[ingredient] - 1;
updatedState.totalPrice = state.totalPrice - INGREDIENT_PRICES[ingredient];
break;
default:
console.log("Action default case");
break;
}

return updatedState;
};

export default reducer;

0 comments on commit 52ad453

Please sign in to comment.