2019-08-02 11:56:53 +00:00
|
|
|
/**
|
|
|
|
* External dependencies
|
|
|
|
*/
|
|
|
|
import { Component } from '@wordpress/element';
|
|
|
|
import { createHigherOrderComponent } from '@wordpress/compose';
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Internal dependencies
|
|
|
|
*/
|
|
|
|
import { getProduct } from '../components/utils';
|
2019-08-30 09:36:06 +00:00
|
|
|
import { formatError } from '../base/utils/errors.js';
|
2019-08-02 11:56:53 +00:00
|
|
|
|
2019-09-05 15:09:31 +00:00
|
|
|
const withProduct = createHigherOrderComponent( ( OriginalComponent ) => {
|
|
|
|
return class WrappedComponent extends Component {
|
|
|
|
constructor() {
|
|
|
|
super( ...arguments );
|
|
|
|
this.state = {
|
|
|
|
error: null,
|
|
|
|
loading: false,
|
|
|
|
product: null,
|
|
|
|
};
|
|
|
|
this.loadProduct = this.loadProduct.bind( this );
|
|
|
|
}
|
2019-08-02 11:56:53 +00:00
|
|
|
|
2019-09-05 15:09:31 +00:00
|
|
|
componentDidMount() {
|
|
|
|
this.loadProduct();
|
|
|
|
}
|
2019-08-02 11:56:53 +00:00
|
|
|
|
2019-09-05 15:09:31 +00:00
|
|
|
componentDidUpdate( prevProps ) {
|
|
|
|
if (
|
2019-09-09 10:52:48 +00:00
|
|
|
prevProps.attributes.productId !==
|
|
|
|
this.props.attributes.productId
|
2019-09-05 15:09:31 +00:00
|
|
|
) {
|
|
|
|
this.loadProduct();
|
2019-08-02 11:56:53 +00:00
|
|
|
}
|
2019-09-05 15:09:31 +00:00
|
|
|
}
|
2019-08-02 11:56:53 +00:00
|
|
|
|
2019-09-05 15:09:31 +00:00
|
|
|
loadProduct() {
|
|
|
|
const { productId } = this.props.attributes;
|
2019-08-02 11:56:53 +00:00
|
|
|
|
2019-09-05 15:09:31 +00:00
|
|
|
if ( ! productId ) {
|
|
|
|
this.setState( { product: null, loading: false, error: null } );
|
|
|
|
return;
|
|
|
|
}
|
2019-08-02 11:56:53 +00:00
|
|
|
|
2019-09-05 15:09:31 +00:00
|
|
|
this.setState( { loading: true } );
|
2019-08-02 11:56:53 +00:00
|
|
|
|
2019-09-05 15:09:31 +00:00
|
|
|
getProduct( productId )
|
|
|
|
.then( ( product ) => {
|
2019-08-02 11:56:53 +00:00
|
|
|
this.setState( { product, loading: false, error: null } );
|
2019-09-05 15:09:31 +00:00
|
|
|
} )
|
|
|
|
.catch( async ( e ) => {
|
2019-09-04 16:07:00 +00:00
|
|
|
const error = await formatError( e );
|
2019-08-02 11:56:53 +00:00
|
|
|
|
|
|
|
this.setState( { product: null, loading: false, error } );
|
|
|
|
} );
|
2019-09-05 15:09:31 +00:00
|
|
|
}
|
2019-08-02 11:56:53 +00:00
|
|
|
|
2019-09-05 15:09:31 +00:00
|
|
|
render() {
|
|
|
|
const { error, loading, product } = this.state;
|
2019-08-02 11:56:53 +00:00
|
|
|
|
2019-09-05 15:09:31 +00:00
|
|
|
return (
|
|
|
|
<OriginalComponent
|
2019-08-02 11:56:53 +00:00
|
|
|
{ ...this.props }
|
|
|
|
error={ error }
|
|
|
|
getProduct={ this.loadProduct }
|
|
|
|
isLoading={ loading }
|
|
|
|
product={ product }
|
2019-09-05 15:09:31 +00:00
|
|
|
/>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
};
|
|
|
|
}, 'withProduct' );
|
2019-08-02 11:56:53 +00:00
|
|
|
|
|
|
|
export default withProduct;
|