Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import React, {Component} from 'react';
- import axios from 'axios';
- import hash from 'object-hash';
- const hasAxiosClient = (baseURL, delay = 0) => WrappedComponent => {
- class HasAxiosClient extends Component {
- // Consumers can track the state of any request done in the hasAxiosClient HOC
- // Nice for "global" loaders - alternatively all requests returns a promise so you can handle
- // it individually. Think of this loading state property as an <ErrorBoundary>.
- state = {
- loading: false
- }
- axiosInstance = axios.create({
- baseURL
- });
- // Keep track of any requests in transit so we can prevent spamming requests
- requestCache = new Map();
- constructor(props) {
- super(props);
- }
- get = (path, params) =>
- this._request({
- url: path,
- method: 'get',
- params
- });
- remove = (path, params) =>
- this._request({
- url: path,
- method: 'delete',
- params
- });
- post = (path, data, params) =>
- this._request({
- url: path,
- method: 'post',
- data,
- params
- });
- put = (path, data, params) =>
- this._request({
- url: path,
- method: 'put',
- data,
- params
- });
- patch = (path, data, params) =>
- this._request({
- url: path,
- method: 'patch',
- data,
- params
- });
- _request(config) {
- this.setState({loading: true});
- const fullPath = `${this.axiosInstance.defaults.baseURL}/${config.url}`;
- // Unique cache key based on request method, url, query params and more
- const cacheKey = hash({path: fullPath, ...config});
- // We dont have a request in transit already, go ahead and make one
- if(!this.requestCache.has(cacheKey)) {
- this.requestCache.set(
- cacheKey,
- this.axiosInstance.request(config)
- // It's possible to set a delay for all requests when using this HOC, nice for debug / dummy data
- .then(response => this._delayResponse(response, delay))
- .then(data => {
- // Clear our request cache - we are done, let others do their stuff
- this.requestCache.delete(cacheKey);
- this.setState({loading: false});
- return data;
- })
- .catch(err => {
- // TODO: delay error responses
- this.requestCache.delete(cacheKey);
- this.setState({loading: false});
- return Promise.reject(err);
- })
- );
- }
- return this.requestCache.get(cacheKey);
- }
- _delayResponse(response, delay = 0) {
- return new Promise(resolve => {
- setTimeout(() => {
- resolve(response.data || {});
- }, delay);
- });
- }
- render() {
- const {loading} = this.state;
- const {
- get,
- remove,
- post,
- put,
- patch
- } = this;
- return (
- <WrappedComponent
- loading={loading}
- get={get}
- delete={remove}
- post={post}
- put={put}
- patch={patch}
- />
- );
- }
- }
- return HasAxiosClient;
- };
- export default hasAxiosClient;
Add Comment
Please, Sign In to add comment