Reputation: 3078
I have the following code which works completely, though one part of it (_FetchJSON) is a custom HOC outside of recompose
(live demo @ https://codepen.io/dakom/pen/zdpPWV?editors=0010)
const LoadingView = () => <div>Please wait...</div>;
const ReadyView = ({ image }) => <div> Got it! <img src={image} /> </div>;
const Page = compose(
_FetchJson,
branch( ({ jsonData }) => !jsonData, renderComponent(LoadingView)),
mapProps(
({jsonData, keyName}) => ({ image: jsonData[keyName] })
)
)(ReadyView);
const ThisPage = <Page request={new Request("//api.github.com/emojis")} keyName="smile" />
//That's it!
ReactDOM.render(ThisPage, document.getElementById("app"));
/*
* Imaginary third party HOC
*/
interface FetchJsonProps {
request: Request;
}
function _FetchJson(WrappedComponent) {
return class extends React.Component<FetchJsonProps> {
componentDidMount() {
fetch(this.props.request)
.then(response => response.json())
.then(this.setState.bind(this));
}
render() {
return <WrappedComponent jsonData={this.state} {...this.props} />
}
}
}
How can I change that _FetchJson
to also work within recompose? Most helpful (not just to me - but for reference) would be two solutions:
lifecycle()
mapPropsStream()
note: I did make an attempt at the lifecycle() way but did not work:
const _FetchJson = compose(
withStateHandlers(undefined,
{
onData: state => ({
jsonData: state
})
}),
lifecycle({
componentDidMount() {
fetch(this.props.request)
.then(response => response.json())
.then(this.props.onData.bind(this));
}
})
);
Upvotes: 4
Views: 3224
Reputation: 9812
There you go:
const fetchJson = compose(
withStateHandlers(null, {
onData: state => data => ({
jsonData: data
})
}),
lifecycle({
componentDidMount() {
fetch(this.props.request)
.then(response => response.json())
.then(data => this.props.onData(data));
}
})
);
Upvotes: 5