Last active
January 30, 2018 23:56
-
-
Save renanlage/cd17eea7ef43c29ebdfa9ab071685d2c to your computer and use it in GitHub Desktop.
This file contains 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 PropTypes from 'prop-types' | |
import filterObject from 'utils/filterObject' | |
// utils/filterObject.js | |
// ------------------------------------ | |
// export default = (obj, allowed) => ( | |
// Object.keys(obj) | |
// .filter(key => allowed.includes(key)) | |
// .reduce((obj, key) => { | |
// obj[key] = raw[key] | |
// return obj | |
// }, {}) | |
// ) | |
const withFetch = (WrappedComponent, url, fields = [], errorMsg = null) => { | |
return class Fetch extends Component | |
state = { | |
data: {}, | |
loading: false, | |
error: null, | |
} | |
componentDidMount() { | |
this.fetch() | |
} | |
fetch() { | |
this.setState({ loading: true, error: null }) | |
axios.get(url) | |
.then(resp => this.setState({ | |
loading: false, | |
data: fields ? filterObject(resp.data, fields) : resp.data, | |
error: null, | |
})) | |
.catch(ex => this.setState({ | |
loading: false, | |
error: errorMsg || ex, | |
})) | |
} | |
render() { | |
return <WrappedComponent loading={this.state.loading} | |
error={this.state.error} | |
{...this.state.data} | |
{...this.props} /> | |
} | |
} | |
} | |
export default withFetch | |
// Exemplo de chamada do component: | |
render() { | |
const PlanetWithFetch = withFetch(Planet) | |
<PlanetWithFetch someProp={123123} /> | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment