react-ketting
Version:
Ketting bindings for React
51 lines • 1.72 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.withResource = void 0;
const React = require("react");
/**
* A Higher order component for listening to Ketting state.
*
* Wrapping your component using withResource will add the following props
* to your component:
*
* * resourceState
* * data
*
* 'resourceState' will refer to the result of a Ketting Resource.get() State
* object, renamed to 'resourceState' to avoid confusion with react state.
* ' data' is the 'body' of the result.
*/
function withResource(WrappedComponent) {
return class extends React.Component {
constructor(props, children) {
super(props, children);
this.state = {
resourceState: null,
data: null,
};
this.onStateUpdateEvent = this.onStateUpdateEvent.bind(this);
}
async componentDidMount() {
const resourceState = await this.props.resource.get();
this.setState({
resourceState,
data: resourceState.data
});
this.props.resource.on('update', this.onStateUpdateEvent);
}
componentWillUnmount() {
this.props.resource.off('update', this.onStateUpdateEvent);
}
async onStateUpdateEvent(state) {
this.setState({
resourceState: state,
data: state.data
});
}
render() {
return React.createElement(WrappedComponent, { resourceState: this.state.resourceState, data: this.state.data, ...this.props });
}
};
}
exports.withResource = withResource;
//# sourceMappingURL=hoc.js.map