component: add error handler by using a higher order component
This commit is contained in:
parent
10e611d2ad
commit
60d5abf809
@ -6,6 +6,7 @@ import BuildControls from '../../components/Burger/BuildControls/BuildControls';
|
||||
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';
|
||||
import axios from '../../axios-orders';
|
||||
|
||||
const INGREDIENT_PRICE = {
|
||||
@ -109,7 +110,7 @@ class BurgerBuilder extends Component {
|
||||
|
||||
axios.post('/order.json', order)
|
||||
.then(response => {
|
||||
this.setState({ loading: false });
|
||||
this.setState({ loading: false, purchasing: false }); // set purchasing: false can close Order Summary dialog
|
||||
})
|
||||
.catch(error => {
|
||||
this.setState({ loading: false });
|
||||
@ -131,7 +132,6 @@ class BurgerBuilder extends Component {
|
||||
purchaseCancalled={this.purchaseCancelHandler}
|
||||
purchaseContinued={this.purchaseContinueHandler}></OrderSummary>;
|
||||
|
||||
|
||||
if (this.state.loading) {
|
||||
orderSummary = <Spinner />
|
||||
}
|
||||
@ -156,4 +156,4 @@ class BurgerBuilder extends Component {
|
||||
};
|
||||
};
|
||||
|
||||
export default BurgerBuilder;
|
||||
export default withErrorHandler(BurgerBuilder, axios);
|
||||
|
42
src/hoc/withErrorHandler/withErrorHandler.js
Normal file
42
src/hoc/withErrorHandler/withErrorHandler.js
Normal file
@ -0,0 +1,42 @@
|
||||
import React, { Component } from 'react';
|
||||
|
||||
import Aux from '../Auxiliary/Auxiliary';
|
||||
import Modal from '../../components/UI/Modal/Modal';
|
||||
|
||||
const withErrorHandler = (WrappedComponent, axios) => {
|
||||
return class extends Component {
|
||||
state = {
|
||||
error: null,
|
||||
}
|
||||
|
||||
componentDidMount() {
|
||||
axios.interceptors.request.use(req => {
|
||||
this.setState({ error: null });
|
||||
return req;
|
||||
});
|
||||
|
||||
axios.interceptors.response.use(res => res, error => {
|
||||
this.setState({ error: error });
|
||||
});
|
||||
}
|
||||
|
||||
errorConfirmedHandler = () => {
|
||||
this.setState({ error: null });
|
||||
}
|
||||
|
||||
render() {
|
||||
return (
|
||||
<Aux>
|
||||
<Modal
|
||||
show={this.state.error}
|
||||
modalClosed={this.errorConfirmedHandler}>
|
||||
{this.state.error ? this.state.error.message : null}
|
||||
</Modal>
|
||||
<WrappedComponent {...this.props} />
|
||||
</Aux>
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export default withErrorHandler;
|
Loading…
Reference in New Issue
Block a user