component: retrieve data from backend and handle error

oscar-http-ajax
oscarzhou 2020-12-25 21:40:04 +13:00
parent 60d5abf809
commit 4a1226e765
2 changed files with 38 additions and 21 deletions

View File

@ -19,16 +19,22 @@ const INGREDIENT_PRICE = {
class BurgerBuilder extends Component {
state = {
ingredients: {
meat: 0,
cheese: 0,
salad: 0,
bacon: 0,
},
ingredients: null,
totalPrice: 0,
purchasable: false,
purchasing: false,
loading: false,
error: false,
}
componentDidMount() {
axios.get('https://react-my-burger-e4645.firebaseio.com/ingredients.json') // remove .json to throw error
.then(res => {
this.setState({ ingredients: res.data });
})
.catch(error => {
this.setState({ error: true});
})
}
updatePurchaseState(ingredients) {
@ -108,7 +114,7 @@ class BurgerBuilder extends Component {
}
};
axios.post('/order.json', order)
axios.post('/order.json', order) // remove .json to throw error
.then(response => {
this.setState({ loading: false, purchasing: false }); // set purchasing: false can close Order Summary dialog
})
@ -126,12 +132,30 @@ class BurgerBuilder extends Component {
disabledInfo[key] = disabledInfo[key] <= 0;
}
let orderSummary = <OrderSummary
let orderSummary = null;
let burger = this.state.error ? <p>Ingredients can't be loaded!</p> : <Spinner />;
if (this.state.ingredients) {
orderSummary = <OrderSummary
ingredients={this.state.ingredients}
price={this.state.totalPrice}
purchaseCancalled={this.purchaseCancelHandler}
purchaseContinued={this.purchaseContinueHandler}></OrderSummary>;
burger = (
<Aux>
<Burger ingredients={this.state.ingredients} />
<BuildControls
ingredientAdded={this.addIngredientHandler}
ingredientRemoved={this.removeIngredientHandler}
ordered={this.purchaseHandler}
disabled={disabledInfo}
purchasable={this.state.purchasable}
price={this.state.totalPrice} />
</Aux>
);
}
if (this.state.loading) {
orderSummary = <Spinner />
}
@ -143,14 +167,7 @@ class BurgerBuilder extends Component {
modalClosed={this.purchaseCancelHandler}>
{orderSummary}
</Modal>
<Burger ingredients={this.state.ingredients} />
<BuildControls
ingredientAdded={this.addIngredientHandler}
ingredientRemoved={this.removeIngredientHandler}
ordered={this.purchaseHandler}
disabled={disabledInfo}
purchasable={this.state.purchasable}
price={this.state.totalPrice} />
{burger}
</Aux>
);
};

View File

@ -9,7 +9,7 @@ const withErrorHandler = (WrappedComponent, axios) => {
error: null,
}
componentDidMount() {
componentWillMount() { // This will happen before child component rendering
axios.interceptors.request.use(req => {
this.setState({ error: null });
return req;