Created
September 15, 2018 21:18
-
-
Save whisher/d9c266df16bf007ef22b8fbbfdd12a42 to your computer and use it in GitHub Desktop.
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, { Component } from 'react'; | |
import axios from 'axios'; | |
const withFetching = (url) => (Component) => | |
class WithFetching extends React.Component { | |
constructor(props) { | |
super(props); | |
this.state = { | |
data: null, | |
isLoading: false, | |
error: null, | |
}; | |
} | |
componentDidMount() { | |
this.setState({ isLoading: true }); | |
axios.get(url) | |
.then(result => this.setState({ | |
data: result.data, | |
isLoading: false | |
})) | |
.catch(error => this.setState({ | |
error, | |
isLoading: false | |
})); | |
} | |
render() { | |
return <Component { ...this.props } { ...this.state } />; | |
} | |
} | |
export default withFetching; | |
import React from 'react'; | |
import withFetching from '../hoc/WithFetch'; | |
const Blog = ({ data, isLoading, error }) => { | |
if (!data) { | |
return <p>No data yet ...</p>; | |
} | |
if (error) { | |
return <p>{error.message}</p>; | |
} | |
if (isLoading) { | |
return <h2>Loading ...</h2>; | |
} | |
return ( | |
<div> | |
{data.results.map((pic,i) => | |
<div key={i}> | |
<img src={pic.picture.medium} /> | |
</div> | |
)} | |
</div> | |
); | |
} | |
export default withFetching('https://randomuser.me/api/?results=50')(Blog); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment