Skip to content

Instantly share code, notes, and snippets.

@chrisryana
Last active June 8, 2020 10:27
Show Gist options
  • Save chrisryana/004b6b5deae98427bdbba7457c0e7606 to your computer and use it in GitHub Desktop.
Save chrisryana/004b6b5deae98427bdbba7457c0e7606 to your computer and use it in GitHub Desktop.
Шаблон HOC для запроса данных на сервер
import React from 'react';
import Spinner from '../components/Spinner';
import ErrorMessage from '../components/ErrorMessage';
import DataService from '../services/DataService';
export default function(WrappedComponent) {
class withDataForComponent extends React.Component {
constructor(props) {
super(props);
this.dataService = new DataService(props.id);
}
state = {
data: [],
loading: false,
error: '',
};
async componentDidMount() {
await this.getData();
}
onLoading = () => {
this.setState({
loading: true,
error: '',
})
}
onLoaded = (result) => {
this.setState({
data: result,
loading: false,
error: '',
})
}
onError = (err) => {
this.setState({
loading: false,
error: err.message,
})
}
getData = async () => {
this.onLoading();
const data = await this.dataService.getData()
.then(this.onLoaded)
.catch(this.onError);
}
render() {
const { loading, error, data } = this.state;
return (
{loading && <Spinner />}
{error && <ErrorMessage message={error} />}
{!loading && !error && <WrappedComponent {...this.props} />}
);
}
}
return withDataForComponent;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment