Im trying to use HOC pattern instead of Object Oriented to avoid redundant code.
The situation is simple as explained below:

In HomePage I have something like this:
const WrappedComponent = Wrapper(Wrapped);
<WrappedComponent { ...this.props } />
In the Wrapper "component", I want to expose a method called foo_method that is an Ajax Call to a WebServer. The result must be written in the state of Wrapped Component.
Now, WrappedComponent can call foo_method but when inside Wrapper, I have no scope of Wrapped state and this.props contains the props of HomePage, not wrapper so I cant create a callback function in Wrapper to be called.
Am I forgetting something in the implementation of HOC?
I think your HOC should look something like this, every WrappedComponent will get result (null while loading and API response after) in the props also wrapped component can call exposed fetch function manually via props.fetchFunction().
function Wrapper(WrappedComponent) {
const fetchData = () => {
return fetch('something');
};
return class extend React.Component {
constructor(props) {
super(props);
this.state = {
result: null,
};
}
componentDidMount() {
fetchData().then((result) => {
this.setState({result});
});
}
render() {
return (
<WrappedComponent
result={this.state.result}
fetchFunction={fetchData}
{...this.props}
/>
);
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With