You can do by creating a HOC which will take two parameters First one is the component and second the promise. and it will return the response and loading in the props Please find the code below for your reference.
HOC
import React, { Component } from "react";
function withErrorBoundary(WrappedComponent, Api) {
return class ErrorBoundary extends Component {
constructor(props) {
super(props);
this.state = { hasError: false, response: null, loading: false };
}
async componentDidMount() {
try {
this.setState({
loading: true
});
const response = await Api;
this.setState({
loading: false,
response
});
console.log("response", response, Api);
} catch (error) {
// throw error here
this.setState({
loading: false
});
}
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
// You can also log the error to an error reporting service
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return (
<WrappedComponent
response={this.state.response}
loading={this.state.loading}
{...this.props}
/>
);
}
};
}
export default withErrorBoundary;
How to use HOC
import ReactDOM from "react-dom";
import React, { Component } from "react";
import withErrorBoundary from "./Error";
class Todo extends Component {
render() {
console.log("this.props.response", this.props.response);
console.log("this.props.loading", this.props.loading);
return <div>hello</div>;
}
}
const Comp = withErrorBoundary(
Todo,
fetch("https://jsonplaceholder.typicode.com/todos/1").then(response =>
response.json()
)
);
ReactDOM.render(<Comp />, document.getElementById("root"));
Please check the codesandbox for your refrence