Last active
July 5, 2019 12:10
-
-
Save stevensacks/cdbc3a9175b053d6f03f0e125afd664f to your computer and use it in GitHub Desktop.
Axios Render Props component inspired by React-Apollo Query/Mutation components
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 axios, {getError} from 'services/axios'; | |
import {Component} from 'react'; | |
import {connect} from 'react-redux'; | |
import {delay} from 'lodash'; | |
import {getAuth} from 'rdx/selectors'; | |
import PropTypes from 'prop-types'; | |
/* eslint-disable no-console */ | |
class Axios extends Component { | |
static propTypes = { | |
auth: PropTypes.object, | |
children: PropTypes.func.isRequired, | |
data: PropTypes.object, | |
instant: PropTypes.bool, | |
method: PropTypes.oneOf(['DELETE', 'GET', 'POST', 'PUT']), | |
url: PropTypes.string.isRequired, | |
}; | |
static defaultProps = { | |
method: 'GET', | |
}; | |
state = {}; | |
componentDidMount() { | |
if (this.props.instant) this.waitForAuth(); | |
} | |
waitForAuth = () => { | |
if (this.props.auth) this.execute(); | |
else delay(this.waitForAuth, 20); | |
}; | |
execute = () => { | |
const {auth, data, method, url} = this.props; | |
const config = { | |
method, | |
url, | |
data, | |
headers: { | |
...auth, | |
}, | |
}; | |
this.setState({loading: true, error: undefined, data: undefined}, () => | |
axios(config) | |
.then(response => { | |
this.setState({ | |
loading: false, | |
error: undefined, | |
data: response.data, | |
}); | |
}) | |
.catch(err => { | |
this.setState({ | |
loading: false, | |
error: getError(err), | |
data: undefined, | |
}); | |
}) | |
); | |
}; | |
render() { | |
const {loading, data, error} = this.state; | |
return this.props.children({ | |
loading, | |
data, | |
error, | |
execute: this.execute, | |
}); | |
} | |
} | |
const mapStateToProps = state => ({ | |
auth: getAuth(state), | |
}); | |
export default connect(mapStateToProps)(Axios); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment