New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

use-http

Package Overview
Dependencies
Maintainers
1
Versions
102
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

use-http - npm Package Compare versions

Comparing version 0.1.71 to 0.1.72

6

dist/Provider.d.ts

@@ -1,9 +0,9 @@

import React, { ReactElement } from 'react';
import { ReactNode } from 'react';
interface FetchProviderProps {
url?: string;
options?: RequestInit;
children: ReactElement;
children: ReactNode;
graphql?: boolean;
}
export declare const Provider: ({ url, options, graphql, children }: FetchProviderProps) => React.ReactElement<any, string | ((props: any) => React.ReactElement<any, string | any | (new (props: any) => React.Component<any, any, any>)> | null) | (new (props: any) => React.Component<any, any, any>)>;
export declare const Provider: ({ url, options, graphql, children }: FetchProviderProps) => JSX.Element;
export {};

@@ -10,12 +10,9 @@ export declare enum HTTPMethod {

}
export interface Options {
url?: string;
onMount?: boolean;
method?: string;
timeout?: number;
baseUrl?: string;
}
export declare type FetchData = (fArg1?: string | object | undefined, fArg2?: string | object | undefined) => Promise<void>;
export declare type BodyOnly = (body: BodyInit) => Promise<void>;
export declare type RouteOnly = (route: string) => Promise<void>;
export declare type RouteAndBodyOnly = (route: string, body: BodyInit) => Promise<void>;
export declare type NoArgs = () => Promise<void>;
declare type FetchData = BodyOnly | RouteOnly | RouteAndBodyOnly | NoArgs;
export declare type FetchCommands = {
get: FetchData;
get: RouteOnly & NoArgs;
post: FetchData;

@@ -26,4 +23,4 @@ patch: FetchData;

delete: FetchData;
query: (query?: string | undefined, variables?: object | undefined) => Promise<void>;
mutate: (mutation?: string | undefined, variables?: object | undefined) => Promise<void>;
query: (query: string, variables?: object) => Promise<void>;
mutate: (mutation: string, variables?: object) => Promise<void>;
abort: () => void;

@@ -38,3 +35,12 @@ };

};
export declare type useFetchArg1 = string | Options & RequestInit;
export declare type UseFetch<TData> = DestructuringCommands<TData> & UseFetchResult<TData>;
export declare type Options = {
onMount?: boolean;
timeout?: number;
url: string;
} & RequestInit;
export declare type OptionsMaybeURL = Omit<Options, 'url'> & {
url?: string;
};
export declare type OptionsOverwriteWithContext = (options: Options) => Options;
export {};
import { Options } from './types';
export declare const useDelete: <TData = any>(url?: string | undefined, options?: Options | undefined) => any[] & {
export declare const useDelete: <TData = any>(url?: string | undefined, options?: Pick<Options, "window" | "body" | "timeout" | "onMount" | "cache" | "credentials" | "headers" | "integrity" | "keepalive" | "method" | "mode" | "redirect" | "referrer" | "referrerPolicy" | "signal"> | undefined) => any[] & {
data: TData | undefined;
loading: boolean;
error: any;
del: import("./types").FetchData;
delete: import("./types").FetchData;
del: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
delete: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
};

@@ -1,3 +0,7 @@

import { Options, UseFetch, useFetchArg1 } from "./types";
export declare function useFetch<TData = any>(arg1?: useFetchArg1, arg2?: Options | RequestInit): UseFetch<TData>;
import { Options, OptionsMaybeURL, UseFetch } from './types';
declare function useFetch<TData = any>(url: string, options?: Omit<Options, 'url'>): UseFetch<TData>;
declare function useFetch<TData = any>(options: Options): UseFetch<TData>;
declare function useFetch<TData = any>(url?: string, options?: Omit<Options, 'url'>): UseFetch<TData>;
declare function useFetch<TData = any>(options?: OptionsMaybeURL): UseFetch<TData>;
export { useFetch };
export default useFetch;

@@ -10,13 +10,2 @@ "use strict";

};
var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
t[p[i]] = s[p[i]];
}
return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {

@@ -30,39 +19,40 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

const utils_1 = require("./utils");
function useFetch(arg1, arg2) {
// TODO: handle context.graphql
function useFetch(urlOrOptions, optionsNoURLs) {
const context = react_1.useContext(FetchContext_1.default);
utils_1.invariant(!!arg1 || !!context.url, 'The first argument of useFetch is required unless you have a global url setup like: <Provider url="https://example.com"></Provider>');
let url = context.url || null;
utils_1.invariant(!!urlOrOptions || !!context.url, 'The first argument of useFetch is required unless you have a global url setup like: <Provider url="https://example.com"></Provider>');
let url = context.url || '';
let options = {};
let onMount = false;
let baseUrl = '';
let method = types_1.HTTPMethod.GET;
const handleOptions = react_1.useCallback((opts) => {
if (true) {
// take out all the things that are not normal `fetch` options
// need to take this out of scope so can set the variables below correctly
let { url, onMount, timeout, baseUrl } = opts, rest = __rest(opts, ["url", "onMount", "timeout", "baseUrl"]);
options = Object.assign({ signal: undefined }, rest);
}
if (context.url)
// let timeout: number = 10 // TODO: not implemented
const handleUseFetchOptions = react_1.useCallback((useFetchOptions) => {
const opts = useFetchOptions || {};
if ('onMount' in opts)
onMount = opts.onMount;
// if (opts.timeout) timeout = opts.timeout
if ('url' in context)
url = context.url;
if (opts.url)
url = opts.url || context.url || '';
if (opts.onMount)
onMount = opts.onMount;
if (opts.method)
method = opts.method;
if (opts.baseUrl)
baseUrl = opts.baseUrl;
if ('url' in opts)
url = opts.url;
}, []);
if (typeof arg1 === 'string') {
// if we have a default url from context, and
// arg1 is a string, and we're not using graphql
// we treat arg1 as a relative route
url = context.url && !context.graphql ? context.url + arg1 : arg1;
if (arg2 && utils_1.isObject(arg2))
handleOptions(arg2);
// ex: useFetch('https://url.com', { onMount: true })
if (utils_1.isString(urlOrOptions) && utils_1.isObject(optionsNoURLs)) {
url = urlOrOptions;
options = utils_1.pullOutRequestInit(optionsNoURLs);
handleUseFetchOptions(optionsNoURLs);
// ex: useFetch('https://url.com')
}
else if (utils_1.isObject(arg1)) {
handleOptions(arg1 || {});
else if (utils_1.isString(urlOrOptions) && optionsNoURLs === undefined) {
url = urlOrOptions;
// ex: useFetch({ onMount: true }) OR useFetch({ url: 'https://url.com' })
}
else if (utils_1.isObject(urlOrOptions)) {
utils_1.invariant(!optionsNoURLs, 'You cannot have a 2nd parameter of useFetch when your first argument is a object config.');
let optsWithURL = urlOrOptions;
utils_1.invariant(!!context.url || !!optsWithURL.url, 'You have to either set a URL in your options config or set a global URL in your <Provider url="https://url.com"></Provider>');
options = utils_1.pullOutRequestInit(urlOrOptions);
handleUseFetchOptions(urlOrOptions);
}
// Provider ex: useFetch({ url: 'https://url.com' }) -- (overwrites global url)
// TODO - Provider: arg1 = oldGlobalOptions => ({ my: 'new local options'}) (overwrite all global options for this instance of useFetch)
const [data, setData] = react_1.useState();

@@ -72,3 +62,3 @@ const [loading, setLoading] = react_1.useState(onMount);

const controller = react_1.useRef();
const fetchData = react_1.useCallback((method) => (fetchArg1, fetchArg2) => __awaiter(this, void 0, void 0, function* () {
const makeFetch = react_1.useCallback((method) => {
if ('AbortController' in window) {

@@ -78,43 +68,60 @@ controller.current = new AbortController();

}
let query = '';
// post | patch | put | etc.
if (utils_1.isObject(fetchArg1) && method.toLowerCase() !== 'get') {
options.body = JSON.stringify(fetchArg1);
// relative routes
let route = '';
function doFetch(routeOrBody, body) {
return __awaiter(this, void 0, void 0, function* () {
// TODO: do the ts types handle if routeOrBody AND body are both objects it will error?
// if not, an invariant(!isObject(routeOrBody) && !isObject(body), 'both arguments cannot be an object')
// POST, PATCH, PUT, DELETE
if (method !== types_1.HTTPMethod.GET) { // TODO: add OPTIONS later
// ex: request.post('/no', { freaking: 'way' })
// ex: reqeust.post('/yes-way')
if (utils_1.isString(routeOrBody)) {
route = routeOrBody;
options.body = JSON.stringify(body || {});
// ex: request.post({ no: 'way' })
}
else if (utils_1.isObject(routeOrBody)) {
utils_1.invariant(!body, `If first argument of ${method.toLowerCase()}() is an object, you cannot have a 2nd argument. 😜`);
options.body = JSON.stringify(routeOrBody || {});
}
// GET
}
else {
utils_1.invariant(!utils_1.isObject(routeOrBody), 'Cannot pass a request body in a GET request');
// ex: request.get('/no?freaking=way')
if (utils_1.isString(routeOrBody))
route = routeOrBody;
}
try {
setLoading(true);
const response = yield fetch(url + route, Object.assign({ method }, context.options, options, { headers: Object.assign({
// default content types http://bit.ly/2N2ovOZ
// Accept: 'application/json',
'Content-Type': 'application/json' }, (context.options || {}).headers, options.headers) }));
let data = null;
try {
data = yield response.json();
}
catch (err) {
data = yield response.text();
}
setData(data);
}
catch (err) {
if (err.name !== 'AbortError')
setError(err);
}
finally {
controller.current = null;
setLoading(false);
}
});
}
else if (baseUrl && typeof fetchArg1 === 'string') {
url = baseUrl + fetchArg1;
if (utils_1.isObject(fetchArg2))
options.body = JSON.stringify(fetchArg2);
}
if (typeof fetchArg1 === 'string' && typeof fetchArg2 === 'string')
query = fetchArg2;
try {
setLoading(true);
const response = yield fetch(url + query, Object.assign({ method }, context.options, options, { headers: Object.assign({
// default content types http://bit.ly/2N2ovOZ
Accept: 'application/json', 'Content-Type': 'application/json' }, (context.options || {}).headers, options.headers) }));
let data = null;
try {
data = yield response.json();
}
catch (err) {
data = yield response.text();
}
setData(data);
}
catch (err) {
if (err.name !== 'AbortError')
setError(err);
}
finally {
controller.current = null;
setLoading(false);
}
}), [url]);
const get = react_1.useCallback(fetchData(types_1.HTTPMethod.GET), []);
const post = react_1.useCallback(fetchData(types_1.HTTPMethod.POST), []);
const patch = react_1.useCallback(fetchData(types_1.HTTPMethod.PATCH), []);
const put = react_1.useCallback(fetchData(types_1.HTTPMethod.PUT), []);
const del = react_1.useCallback(fetchData(types_1.HTTPMethod.DELETE), []);
return doFetch;
}, [url]);
const get = react_1.useCallback(makeFetch(types_1.HTTPMethod.GET), []);
const post = react_1.useCallback(makeFetch(types_1.HTTPMethod.POST), []);
const patch = react_1.useCallback(makeFetch(types_1.HTTPMethod.PATCH), []);
const put = react_1.useCallback(makeFetch(types_1.HTTPMethod.PUT), []);
const del = react_1.useCallback(makeFetch(types_1.HTTPMethod.DELETE), []);
const query = react_1.useCallback((query, variables) => post({ query, variables }), []);

@@ -126,6 +133,21 @@ const mutate = react_1.useCallback((mutation, variables) => post({ mutation, variables }), []);

const request = react_1.useMemo(() => ({ get, post, patch, put, del, delete: del, abort, query, mutate }), []);
// handling onMount
react_1.useEffect(() => {
const methodName = method.toLowerCase();
if (onMount)
request[methodName]();
const methodName = ((options.method || '') || types_1.HTTPMethod.GET).toUpperCase();
if (!!url && onMount && methodName !== types_1.HTTPMethod.GET) {
const req = request[methodName.toLowerCase()];
req(url, options.body);
}
else if (!url && onMount && methodName !== types_1.HTTPMethod.GET) {
const req = request[methodName.toLowerCase()];
req(options.body);
}
else if (!!url && onMount) {
const req = request[methodName.toLowerCase()];
req(url);
}
else if (onMount) {
const req = request[methodName.toLowerCase()];
req();
}
}, []);

@@ -132,0 +154,0 @@ return Object.assign([data, loading, error, request], Object.assign({ data, loading, error, request }, request));

import { Options } from './types';
export declare const useGet: <TData = any>(url?: string | undefined, options?: Options | undefined) => any[] & {
export declare const useGet: <TData = any>(url?: string | undefined, options?: Pick<Options, "window" | "body" | "timeout" | "onMount" | "cache" | "credentials" | "headers" | "integrity" | "keepalive" | "method" | "mode" | "redirect" | "referrer" | "referrerPolicy" | "signal"> | undefined) => any[] & {
data: TData | undefined;
loading: boolean;
error: any;
get: import("./types").FetchData;
get: import("./types").RouteOnly & import("./types").NoArgs;
};

@@ -65,9 +65,9 @@ export declare const useMutation: <TData = any>(arg1: string | TemplateStringsArray, arg2?: string | undefined) => any[] & {

flat<U>(depth?: number | undefined): any[];
get: import("./types").FetchData;
post: import("./types").FetchData;
patch: import("./types").FetchData;
put: import("./types").FetchData;
del: import("./types").FetchData;
delete: import("./types").FetchData;
query: (query?: string | undefined, variables?: object | undefined) => Promise<void>;
get: import("./types").RouteOnly & import("./types").NoArgs;
post: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
patch: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
put: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
del: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
delete: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
query: (query: string, variables?: object | undefined) => Promise<void>;
abort: () => void;

@@ -74,0 +74,0 @@ data?: TData | undefined;

@@ -15,8 +15,4 @@ "use strict";

const context = react_1.useContext(_1.FetchContext);
// we should only need to check this on 1st render
react_1.useEffect(() => {
if (Array.isArray(arg1)) {
utils_1.invariant(!!context.url, 'You need to wrap your application with <Provider url="https://your-site.com"></Provider>');
}
}, []);
utils_1.useURLRequiredInvariant(!!context.url && Array.isArray(arg1), 'useMutation');
utils_1.useURLRequiredInvariant(!!context.url && utils_1.isString(arg1) && !arg2, 'useMutation', 'OR you need to do useMutation("https://example.com", `your graphql mutation`)');
// regular no context: useMutation('https://example.com', `graphql MUTATION`)

@@ -23,0 +19,0 @@ let url = arg1;

import { Options } from './types';
export declare const usePatch: <TData = any>(url?: string | undefined, options?: Options | undefined) => any[] & {
export declare const usePatch: <TData = any>(url?: string | undefined, options?: Pick<Options, "window" | "body" | "timeout" | "onMount" | "cache" | "credentials" | "headers" | "integrity" | "keepalive" | "method" | "mode" | "redirect" | "referrer" | "referrerPolicy" | "signal"> | undefined) => any[] & {
data: TData | undefined;
loading: boolean;
error: any;
patch: import("./types").FetchData;
patch: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
};
import { Options } from './types';
export declare const usePost: <TData = any>(url?: string | undefined, options?: Options | undefined) => any[] & {
export declare const usePost: <TData = any>(url?: string | undefined, options?: Pick<Options, "window" | "body" | "timeout" | "onMount" | "cache" | "credentials" | "headers" | "integrity" | "keepalive" | "method" | "mode" | "redirect" | "referrer" | "referrerPolicy" | "signal"> | undefined) => any[] & {
data: TData | undefined;
loading: boolean;
error: any;
post: import("./types").FetchData;
post: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
};
import { Options } from './types';
export declare const usePut: <TData = any>(url?: string | undefined, options?: Options | undefined) => any[] & {
export declare const usePut: <TData = any>(url?: string | undefined, options?: Pick<Options, "window" | "body" | "timeout" | "onMount" | "cache" | "credentials" | "headers" | "integrity" | "keepalive" | "method" | "mode" | "redirect" | "referrer" | "referrerPolicy" | "signal"> | undefined) => any[] & {
data: TData | undefined;
loading: boolean;
error: any;
put: import("./types").FetchData;
put: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
};

@@ -65,9 +65,9 @@ export declare const useQuery: <TData = any>(arg1: string | TemplateStringsArray, arg2?: string | undefined) => any[] & {

flat<U>(depth?: number | undefined): any[];
get: import("./types").FetchData;
post: import("./types").FetchData;
patch: import("./types").FetchData;
put: import("./types").FetchData;
del: import("./types").FetchData;
delete: import("./types").FetchData;
mutate: (mutation?: string | undefined, variables?: object | undefined) => Promise<void>;
get: import("./types").RouteOnly & import("./types").NoArgs;
post: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
patch: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
put: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
del: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
delete: import("./types").BodyOnly | import("./types").RouteOnly | import("./types").RouteAndBodyOnly | import("./types").NoArgs;
mutate: (mutation: string, variables?: object | undefined) => Promise<void>;
abort: () => void;

@@ -74,0 +74,0 @@ data?: TData | undefined;

@@ -15,8 +15,4 @@ "use strict";

const context = react_1.useContext(_1.FetchContext);
// we should only need to check this on 1st render
react_1.useEffect(() => {
if (Array.isArray(arg1)) {
utils_1.invariant(!!context.url, 'You need to wrap your application with <Provider url="https://your-site.com"></Provider>');
}
}, []);
utils_1.useURLRequiredInvariant(!!context.url && Array.isArray(arg1), 'useQuery');
utils_1.useURLRequiredInvariant(!!context.url && utils_1.isString(arg1) && !arg2, 'useQuery', 'OR you need to do useQuery("https://example.com", `your graphql query`)');
// regular no context: useQuery('https://example.com', `graphql QUERY`)

@@ -23,0 +19,0 @@ let url = arg1;

@@ -1,4 +0,10 @@

export declare function useURLRequiredInvariant(condition: boolean, method: string): void;
export declare function useURLRequiredInvariant(condition: boolean, method: string, optionalMessage?: string): void;
export declare const useExampleURL: () => string;
export declare const isString: (x: any) => boolean;
/**
* Makes an object that will match the standards of a normal fetch's options
* aka: pulls out all useFetch's special options like "onMount"
*/
export declare const pullOutRequestInit: (options?: {} | undefined) => RequestInit;
/**
* Determines if the given param is an object. {}

@@ -5,0 +11,0 @@ * @param obj

@@ -8,3 +8,3 @@ "use strict";

const use_ssr_1 = __importDefault(require("use-ssr"));
function useURLRequiredInvariant(condition, method) {
function useURLRequiredInvariant(condition, method, optionalMessage) {
const exampleURL = exports.useExampleURL();

@@ -14,3 +14,4 @@ react_1.useEffect(() => {

unless you wrap your app like:\n
<Provider url="${exampleURL}"><App /></Provider>`);
<Provider url="${exampleURL}"><App /></Provider>\n
${optionalMessage}`);
}, []);

@@ -23,3 +24,34 @@ }

};
exports.isString = (x) => typeof x === 'string';
// TODO: come back and fix the "anys" in this http://bit.ly/2Lm3OLi
/**
* Makes an object that will match the standards of a normal fetch's options
* aka: pulls out all useFetch's special options like "onMount"
*/
exports.pullOutRequestInit = (options) => {
let opts = {};
if (options)
opts = options;
const requestInitFields = [
'body',
'cache',
'credentials',
'headers',
'integrity',
'keepalive',
'method',
'mode',
'redirect',
'referrer',
'referrerPolicy',
'signal',
'window',
];
return requestInitFields.reduce((acc, key) => {
if (key in opts)
acc[key] = opts[key];
return acc;
}, {});
};
/**
* Determines if the given param is an object. {}

@@ -26,0 +58,0 @@ * @param obj

{
"name": "use-http",
"version": "0.1.71",
"version": "0.1.72",
"homepage": "https://codesandbox.io/embed/km04k9k9x5",

@@ -5,0 +5,0 @@ "main": "dist/index.js",

@@ -110,5 +110,5 @@

```jsx
const request = useFetch({
baseUrl: 'https://example.com'
})
var request = useFetch({ url: 'https://example.com' })
// OR
var request = useFetch('https://example.com')

@@ -143,3 +143,3 @@ request.post('/todos', {

const githubRepos = useFetch({
baseUrl: `https://api.github.com/search/repositories?q=`
url: `https://api.github.com/search/repositories?q=`
})

@@ -336,3 +336,3 @@

| `onMount` | Once the component mounts, the http request will run immediately | false |
| `baseUrl` | Allows you to set a base path so relative paths can be used for each request :) | empty string |
| `url` | Allows you to set a base path so relative paths can be used for each request :) | empty string |

@@ -356,4 +356,3 @@ ```jsx

// accepts all `fetch` options such as headers, method, etc.
url: 'https://example.com',
baseUrl: 'https://example.com',
url: 'https://example.com', // used to be `baseUrl`
onMount: true

@@ -366,4 +365,3 @@ })

// accepts all `fetch` options such as headers, method, etc.
url: 'https://example.com',
baseUrl: 'https://example.com',
url: 'https://example.com', // used to be `baseUrl`
onMount: true

@@ -370,0 +368,0 @@ })

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc