Вы можете создать HO C, который будет принимать два параметра. Первый - это компонент, а второй - обещание. и он вернет ответ и загрузку в реквизитах. Пожалуйста, найдите код для справки ниже.
HO C
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;
Как использовать HO C
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"));
Пожалуйста, проверьте коды и поле для вашей ссылки