Skip to content

Instantly share code, notes, and snippets.

@renanlage
Last active January 30, 2018 23:56
Show Gist options
  • Save renanlage/cd17eea7ef43c29ebdfa9ab071685d2c to your computer and use it in GitHub Desktop.
Save renanlage/cd17eea7ef43c29ebdfa9ab071685d2c to your computer and use it in GitHub Desktop.
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