Add ResourceContainer component which provides a loaded resource to its child
authorFrank Bessou <frank.bessou@logilab.fr>
Fri, 05 May 2017 12:17:18 +0200
changeset 184 d4466da07974
parent 183 faaa51e8a501
child 185 cfff71efc852
Add ResourceContainer component which provides a loaded resource to its child
src/components/Resource.js
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/components/Resource.js	Fri May 05 12:17:18 2017 +0200
@@ -0,0 +1,49 @@
+import * as React from 'react';
+import hypermediaClient from '../services/hypermedia';
+import {PropTypes} from 'prop-types';
+
+export class ResourceContainer extends React.Component {
+    constructor(props) {
+        super(props);
+        this.state = this.getInitialState();
+        this.hypermediaClient = hypermediaClient;
+    }
+
+    getInitialState() {
+        return {resource: null};
+    }
+
+    initResource(route) {
+        return this.hypermediaClient.getResource(route).then(
+            resource => {
+                this.setState({resource: resource});
+            });
+    }
+
+    componentWillReceiveProps(nextProps) {
+        const newRoute = nextProps.url;
+        if (newRoute !== this.props.url) {
+            this.setState(this.getInitialState());
+            this.initResource(newRoute);
+        }
+    }
+
+    componentDidMount() {
+        this.initResource(this.props.url);
+    }
+
+    render() {
+        if (!this.state.resource) {
+            return <div>Loading...</div>;
+        }
+        const Component = this.props.component;
+        const childProps = this.props.childProps || {};
+        return <Component {...childProps} resource={this.state.resource} />;
+    }
+
+}
+ResourceContainer.propTypes = {
+    childProps: PropTypes.object,
+    url: PropTypes.string.isRequired,
+    component: PropTypes.func.isRequired,
+};