react-http-fetch
Version:
An http library for React JS built on top of native JS fetch
46 lines (45 loc) • 2.04 kB
JavaScript
import React, { createContext, useContext, memo, useMemo } from 'react';
import { useCompareMemo } from '../shared';
import { defaultClientProps, defaultHttpReqConfig, defaultCacheStore } from './defaults';
import fastCompare from 'react-fast-compare';
import { HttpCacheService } from '../cache';
import { HttpCacheStorePrefixDecorator } from '../cache/prefix-decorator';
/**
* The context to provide the default http client configuration.
*/
export var HttpClientContext = createContext(defaultClientProps);
/**
* The provider for the default http client configuration.
*/
var HttpClientConfigProvider = function (_a) {
var config = _a.config, children = _a.children;
/**
* The merged http config.
*/
var mergedHttpConfig = useCompareMemo(function () {
var cacheStore = config.cacheStore || defaultCacheStore;
var prefixedCacheStore = new HttpCacheStorePrefixDecorator(cacheStore, config.cacheStorePrefix, config.cacheStoreSeparator);
var cache = new HttpCacheService(prefixedCacheStore);
return {
baseUrl: config.baseUrl || defaultHttpReqConfig.baseUrl,
responseParser: config.responseParser || defaultHttpReqConfig.responseParser,
reqOptions: config.reqOptions || defaultHttpReqConfig.reqOptions,
requestBodySerializer: config.requestBodySerializer || defaultHttpReqConfig.requestBodySerializer,
cache: cache,
};
}, [config], fastCompare);
var publicApi = useMemo(function () { return ({
config: mergedHttpConfig,
}); }, [mergedHttpConfig]);
return React.createElement(HttpClientContext.Provider, { value: publicApi }, children);
};
HttpClientConfigProvider.displayName = 'HttpClientProvider';
var memoizedProvider = memo(HttpClientConfigProvider);
export { memoizedProvider as HttpClientConfigProvider };
/**
* A utility hook to get the http client config context.
*/
export var useHttpClientConfig = function () {
var config = useContext(HttpClientContext);
return config;
};