Last active
June 8, 2020 10:27
-
-
Save chrisryana/004b6b5deae98427bdbba7457c0e7606 to your computer and use it in GitHub Desktop.
Шаблон HOC для запроса данных на сервер
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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