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.79 to 0.1.80

5

dist/index.d.ts
export { default } from './useFetch';
export * from './useFetch';
export * from './useGet';
export * from './usePost';
export * from './usePut';
export * from './usePatch';
export * from './useDelete';
export * from './useMutation';

@@ -9,0 +4,0 @@ export * from './useQuery';

@@ -9,7 +9,2 @@ "use strict";

__export(require("./useFetch"));
__export(require("./useGet"));
__export(require("./usePost"));
__export(require("./usePut"));
__export(require("./usePatch"));
__export(require("./useDelete"));
__export(require("./useMutation"));

@@ -16,0 +11,0 @@ __export(require("./useQuery"));

7

dist/makeRouteAndOptions.js

@@ -5,6 +5,7 @@ "use strict";

const utils_1 = require("./utils");
const { GET, OPTIONS } = types_1.HTTPMethod;
function makeRouteAndOptions(initialOptions, method, controller, routeOrBody, bodyAs2ndParam) {
utils_1.invariant(!(utils_1.isObject(routeOrBody) && utils_1.isObject(bodyAs2ndParam)), `If first argument of ${method.toLowerCase()}() is an object, you cannot have a 2nd argument. 😜`);
utils_1.invariant(!(method === types_1.HTTPMethod.GET && utils_1.isObject(routeOrBody)), `You can only have query params as 1st argument of request.get()`);
utils_1.invariant(!(method === types_1.HTTPMethod.GET && bodyAs2ndParam !== undefined), `You can only have query params as 1st argument of request.get()`);
utils_1.invariant(!(method === GET && utils_1.isObject(routeOrBody)), `You can only have query params as 1st argument of request.get()`);
utils_1.invariant(!(method === GET && bodyAs2ndParam !== undefined), `You can only have query params as 1st argument of request.get()`);
const route = (() => {

@@ -40,3 +41,3 @@ if (utils_1.isBrowser && routeOrBody instanceof URLSearchParams)

}
if (method === types_1.HTTPMethod.GET)
if (method === GET || method === OPTIONS)
delete opts.body;

@@ -43,0 +44,0 @@ return opts;

@@ -5,3 +5,3 @@ export declare enum HTTPMethod {

HEAD = "HEAD",
OTIONS = "OPTIONS",
OPTIONS = "OPTIONS",
PATCH = "PATCH",

@@ -26,3 +26,3 @@ POST = "POST",

};
export interface FetchCommands {
export interface ReqMethods {
get: (route?: string) => Promise<any>;

@@ -38,12 +38,21 @@ post: FetchData;

}
export declare type DestructuringCommands<TData = any> = [TData | undefined, boolean, any, FetchCommands];
export interface UseFetchBaseResult<TData = any> {
export interface Data<TData> {
data: TData | undefined;
}
export interface ReqBase<TData> {
data: TData | undefined;
loading: boolean;
error: Error;
}
export declare type UseFetchResult<TData = any> = UseFetchBaseResult<TData> & FetchCommands & {
request: FetchCommands;
export interface Res<TData> extends Response {
data: TData | undefined;
}
export declare type Req<TData = any> = ReqMethods & ReqBase<TData>;
export declare type UseFetchArgs = [(string | OptionsMaybeURL)?, NoUrlOptions?];
export declare type UseFetchArrayReturn<TData> = [Req<TData>, Res<TData>, boolean, Error];
export declare type UseFetchObjectReturn<TData> = ReqBase<TData> & ReqMethods & {
request: Req<TData>;
response: Res<TData>;
};
export declare type UseFetch<TData> = DestructuringCommands<TData> & UseFetchResult<TData>;
export declare type UseFetch<TData> = UseFetchArrayReturn<TData> & UseFetchObjectReturn<TData>;
export interface CustomOptions {

@@ -53,2 +62,4 @@ onMount?: boolean;

url: string;
loading?: boolean;
data?: any;
}

@@ -55,0 +66,0 @@ export declare type Options = CustomOptions & Omit<RequestInit, 'body'> & {

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

HTTPMethod["HEAD"] = "HEAD";
HTTPMethod["OTIONS"] = "OPTIONS";
HTTPMethod["OPTIONS"] = "OPTIONS";
HTTPMethod["PATCH"] = "PATCH";

@@ -11,0 +11,0 @@ HTTPMethod["POST"] = "POST";

@@ -40,5 +40,18 @@ "use strict";

}, [urlOrOptions, optionsNoURLs]);
return { url, onMount };
const loading = react_1.useMemo(() => {
if (utils_1.isObject(urlOrOptions))
return !!urlOrOptions.loading || !!urlOrOptions.onMount;
if (utils_1.isObject(optionsNoURLs))
return !!optionsNoURLs.loading || !!optionsNoURLs.onMount;
return false;
}, [urlOrOptions, optionsNoURLs]);
const data = react_1.useMemo(() => {
if (utils_1.isObject(urlOrOptions))
return urlOrOptions.data;
if (utils_1.isObject(optionsNoURLs))
return optionsNoURLs.data;
}, [urlOrOptions, optionsNoURLs]);
return { url, onMount, loading, data };
}
exports.default = useCustomOptions;
//# sourceMappingURL=useCustomOptions.js.map

@@ -1,5 +0,4 @@

import { OptionsMaybeURL, UseFetch } from './types';
import { NoUrlOptions } from './types';
declare function useFetch<TData = any>(urlOrOptions?: string | OptionsMaybeURL, optionsNoURLs?: NoUrlOptions): UseFetch<TData>;
import { UseFetch, UseFetchArgs } from './types';
declare function useFetch<TData = any>(...args: UseFetchArgs): UseFetch<TData>;
export { useFetch };
export default useFetch;

@@ -10,2 +10,13 @@ "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,9 +41,10 @@ return (mod && mod.__esModule) ? mod : { "default": mod };

// TODO: handle context.graphql
function useFetch(urlOrOptions, optionsNoURLs) {
function useFetch(...args) {
const _a = useCustomOptions_1.default(...args), { url, onMount } = _a, defaults = __rest(_a, ["url", "onMount"]);
const requestInit = useRequestInit_1.default(...args);
const { isBrowser, isServer } = use_ssr_1.default();
const { onMount, url } = useCustomOptions_1.default(urlOrOptions, optionsNoURLs);
const requestInit = useRequestInit_1.default(urlOrOptions, optionsNoURLs);
const controller = react_1.useRef();
const data = react_1.useRef();
const [loading, setLoading] = react_1.useState(onMount || false);
const res = react_1.useRef();
const data = react_1.useRef(defaults.data);
const [loading, setLoading] = react_1.useState(defaults.loading);
const [error, setError] = react_1.useState();

@@ -47,8 +59,8 @@ const makeFetch = react_1.useCallback((method) => {

return; // TODO: for now, we don't do anything on the server
const response = yield fetch(`${url}${route}`, options);
res.current = yield fetch(`${url}${route}`, options);
try {
data.current = yield response.json();
data.current = yield res.current.json();
}
catch (err) {
data.current = (yield response.text()); // FIXME: should not be `any` type
data.current = (yield res.current.text()); // FIXME: should not be `any` type
}

@@ -67,29 +79,29 @@ }

}, [
/* url, isBrowser, requestInit, isServer */
url, isBrowser, requestInit, isServer
]);
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 }), [post]);
const mutate = react_1.useCallback((mutation, variables) => post({ mutation, variables }), [post]);
const abort = react_1.useCallback(() => {
controller.current && controller.current.abort();
}, []);
const request = react_1.useMemo(() => ({
get,
const post = makeFetch(types_1.HTTPMethod.POST);
const del = makeFetch(types_1.HTTPMethod.DELETE);
const request = {
get: makeFetch(types_1.HTTPMethod.GET),
post,
patch,
put,
patch: makeFetch(types_1.HTTPMethod.PATCH),
put: makeFetch(types_1.HTTPMethod.PUT),
del,
delete: del,
abort,
query,
mutate,
}), [get, post, patch, put, del, abort, query, mutate]);
abort() {
controller.current && controller.current.abort();
},
query: (query, variables) => post({ query, variables }),
mutate: (mutation, variables) => post({ mutation, variables }),
loading: loading,
error,
data: data.current,
};
const response = Object.assign({ data: data.current }, res.current);
// handling onMount
const mounted = react_1.useRef(false);
react_1.useEffect(() => {
if (!onMount)
if (!onMount || mounted.current)
return;
mounted.current = true;
const methodName = requestInit.method || types_1.HTTPMethod.GET;

@@ -106,5 +118,5 @@ const methodLower = methodName.toLowerCase();

}, [
/*onMount, requestInit.body, requestInit.method, request, url*/
onMount, requestInit.body, requestInit.method, url,
]);
return Object.assign([data.current, loading, error, request], Object.assign({ data: data.current, loading, error, request }, request));
return Object.assign([request, response, loading, error], Object.assign({ request, response: response }, request));
}

@@ -111,0 +123,0 @@ exports.useFetch = useFetch;

@@ -1,8 +0,8 @@

import { UseFetchBaseResult } from './types';
import { ReqBase } from './types';
declare type ArrayDestructure<TData = any> = [TData | undefined, boolean, Error, (variables?: object) => Promise<any>];
interface ObjectDestructure<TData = any> extends UseFetchBaseResult<TData> {
interface ObjectDestructure<TData = any> extends ReqBase<TData> {
mutate: (variables?: object) => Promise<any>;
}
declare type UseMutation = ArrayDestructure & ObjectDestructure;
export declare const useMutation: <TData = any>(urlOrMutation: string | TemplateStringsArray, mutationArg?: string | undefined) => UseMutation;
declare type UseMutation<TData = any> = ArrayDestructure<TData> & ObjectDestructure<TData>;
export declare const useMutation: <TData = any>(urlOrMutation: string | TemplateStringsArray, mutationArg?: string | undefined) => UseMutation<TData>;
export {};
"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 __importStar = (this && this.__importStar) || function (mod) {

@@ -16,3 +27,3 @@ if (mod && mod.__esModule) return mod;

utils_1.useURLRequiredInvariant(!!context.url && Array.isArray(urlOrMutation), 'useMutation');
utils_1.useURLRequiredInvariant(!!context.url && utils_1.isString(urlOrMutation) && !mutationArg, 'useMutation', 'OR you need to do useMutation("https://example.com", `your graphql mutation`)');
utils_1.useURLRequiredInvariant(!!context.url || utils_1.isString(urlOrMutation) && !mutationArg, 'useMutation', 'OR you need to do useMutation("https://example.com", `your graphql mutation`)');
// regular no context: useMutation('https://example.com', `graphql MUTATION`)

@@ -32,11 +43,7 @@ let url = urlOrMutation;

}
const request = _1.default(url);
const _a = _1.default(url), { loading, error } = _a, request = __rest(_a, ["loading", "error"]);
const mutate = react_1.useCallback((inputs) => request.mutate(MUTATION, inputs), [MUTATION, request]);
return Object.assign([request.data, request.loading, request.error, mutate], {
data: request.data,
loading: request.loading,
error: request.error,
mutate,
});
const data = (request.data || { data: undefined }).data;
return Object.assign([data, loading, error, mutate], { data, loading, error, mutate });
};
//# sourceMappingURL=useMutation.js.map

@@ -1,8 +0,8 @@

import { UseFetchBaseResult } from './types';
import { ReqBase } from './types';
declare type ArrayDestructure<TData = any> = [TData | undefined, boolean, Error, (variables?: object) => Promise<any>];
interface ObjectDestructure<TData = any> extends UseFetchBaseResult<TData> {
interface ObjectDestructure<TData = any> extends ReqBase<TData> {
query: (variables?: object) => Promise<any>;
}
declare type UseQuery = ArrayDestructure & ObjectDestructure;
export declare const useQuery: <TData = any>(urlOrQuery: string | TemplateStringsArray, queryArg?: string | undefined) => UseQuery;
declare type UseQuery<TData = any> = ArrayDestructure<TData> & ObjectDestructure<TData>;
export declare const useQuery: <TData = any>(urlOrQuery: string | TemplateStringsArray, queryArg?: string | undefined) => UseQuery<TData>;
export {};
"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 __importStar = (this && this.__importStar) || function (mod) {

@@ -16,3 +27,3 @@ if (mod && mod.__esModule) return mod;

utils_1.useURLRequiredInvariant(!!context.url && Array.isArray(urlOrQuery), 'useQuery');
utils_1.useURLRequiredInvariant(!!context.url && utils_1.isString(urlOrQuery) && !queryArg, 'useQuery', 'OR you need to do useQuery("https://example.com", `your graphql query`)');
utils_1.useURLRequiredInvariant(!!context.url || utils_1.isString(urlOrQuery) && !queryArg, 'useQuery', 'OR you need to do useQuery("https://example.com", `your graphql query`)');
// regular no context: useQuery('https://example.com', `graphql QUERY`)

@@ -32,11 +43,7 @@ let url = urlOrQuery;

}
const request = _1.default(url);
const _a = _1.default(url), { loading, error } = _a, request = __rest(_a, ["loading", "error"]);
const query = react_1.useCallback((variables) => request.query(QUERY, variables), [QUERY, request]);
return Object.assign([request.data, request.loading, request.error, query], {
data: request.data,
loading: request.loading,
error: request.error,
query,
});
const data = (request.data || { data: undefined }).data;
return Object.assign([data, loading, error, query], { data, loading, error, query });
};
//# sourceMappingURL=useQuery.js.map
{
"name": "use-http",
"version": "0.1.79",
"version": "0.1.80",
"homepage": "http://use-http.com",

@@ -24,14 +24,14 @@ "main": "dist/index.js",

"@types/node": "^12.0.10",
"@types/react": "^16.8.23",
"@types/react": "16.8.23",
"@types/react-dom": "^16.8.4",
"@typescript-eslint/eslint-plugin": "^1.11.0",
"@typescript-eslint/parser": "^1.11.0",
"@typescript-eslint/eslint-plugin": "^2.0.0",
"@typescript-eslint/parser": "^2.0.0",
"eslint": "^6.0.1",
"eslint-config-prettier": "4.3.0",
"eslint-plugin-jest": "22.13.6",
"eslint-plugin-jest-formatting": "0.1.0",
"eslint-config-prettier": "6.2.0",
"eslint-plugin-jest": "22.16.0",
"eslint-plugin-jest-formatting": "1.1.0",
"eslint-plugin-jsx-a11y": "^6.2.1",
"eslint-plugin-prettier": "^3.1.0",
"eslint-plugin-react": "^7.14.2",
"eslint-plugin-react-hooks": "^1.6.1",
"eslint-plugin-react-hooks": "^2.0.0",
"eslint-plugin-sonarjs": "^0.4.0",

@@ -38,0 +38,0 @@ "eslint-watch": "^5.1.2",

@@ -21,3 +21,3 @@ <a href="http://use-http.com">

<a href="https://www.npmjs.com/package/use-http">
<img src="https://img.shields.io/npm/dm/use-http.svg" />
<img src="https://img.shields.io/npm/dt/use-http.svg" />
</a>

@@ -83,3 +83,2 @@ <a href="https://lgtm.com/projects/g/alex-cory/use-http/context:javascript">

<li><a target="_blank" rel="noopener noreferrer" href='https://codesandbox.io/embed/km04k9k9x5'>useFetch + create-react-app</a></li>
<li><a target="_blank" rel="noopener noreferrer" href='https://codesandbox.io/s/useget-with-provider-c78w2'>useGet + < Provider /></a></li>
</ul>

@@ -96,12 +95,16 @@ </details>

const request = useFetch('https://example.com')
const [request, response] = useFetch('https://example.com')
// on mount, initialize the todos
// componentDidMount
const mounted = useRef(false)
useEffect(() => {
initializeTodos()
}, [])
if (!mounted.current) {
initializeTodos()
mounted.current= true
}
})
async function initializeTodos() {
const initialTodos = await request.get('/todos')
setTodos(initialTodos)
if (response.ok) setTodos(initialTodos)
}

@@ -113,3 +116,3 @@

})
setTodos(oldTodos => [...oldTodos, newTodo])
if (response.ok) setTodos([...todos, newTodo])
}

@@ -119,3 +122,3 @@

<>
<button onClick={addTodo}>Add Todo</button>
<button onClick={ addTodo }>Add Todo</button>
{request.error && 'Error!'}

@@ -132,3 +135,3 @@ {request.loading && 'Loading...'}

<details><summary><b>Basic Usage (no managed state) <code>useFetch</code></b></summary>
<details open><summary><b>Basic Usage (no managed state) <code>useFetch</code></b></summary>

@@ -140,10 +143,11 @@ ```js

const options = { // accepts all `fetch` options
onMount: true // will fire on componentDidMount
onMount: true, // will fire on componentDidMount (GET by default)
data: [] // default for `data` will be an array instead of undefined
}
const todos = useFetch('https://example.com/todos', options)
const { loading, error, data, post } = useFetch('https://example.com/todos', options)
function addTodo() {
todos.post({
title: 'no way',
post({
title: 'no way'
})

@@ -155,5 +159,5 @@ }

<button onClick={addTodo}>Add Todo</button>
{request.error && 'Error!'}
{request.loading && 'Loading...'}
{(todos.data || []).length > 0 && todos.data.map(todo => (
{error && 'Error!'}
{loading && 'Loading...'}
{!loading && data.map(todo => (
<div key={todo.id}>{todo.title}</div>

@@ -167,9 +171,46 @@ )}

<details><summary><b>Destructured <code>useFetch</code></b></summary>
<details open><summary><b>Destructured <code>useFetch</code></b></summary>
```js
var [data, loading, error, request] = useFetch('https://example.com')
var [request, response, loading, error] = useFetch('https://example.com')
// want to use object destructuring? You can do that too
var { data, loading, error, request } = useFetch('https://example.com')
var {
request,
response,
loading,
error,
data,
get,
post,
put,
patch,
delete // don't destructure `delete` though, it's a keyword
del, // <- that's why we have this (del). or use `request.delete`
mutate, // GraphQL
query, // GraphQL
abort
} = useFetch('https://example.com')
var {
loading,
error,
data,
get,
post,
put,
patch,
delete // don't destructure `delete` though, it's a keyword
del, // <- that's why we have this (del). or use `request.delete`
mutate, // GraphQL
query, // GraphQL
abort
} = request
var {
data,
ok,
headers,
...restOfHttpResponse // everything you would get in a response from an http request
} = response
```

@@ -194,21 +235,2 @@ </details>

<details><summary><b><code>useGet</code>, <code>usePost</code>, <code>usePatch</code>, <code>usePut</code>, <code>useDelete</code></b></summary>
```jsx
import { useGet, usePost, usePatch, usePut, useDelete } from 'use-http'
const [data, loading, error, patch] = usePatch({
url: 'https://example.com',
headers: {
'Accept': 'application/json; charset=UTF-8'
}
})
patch({
yes: 'way',
})
```
</details>
<details><summary><b>Abort <code>useFetch</code></b></summary>

@@ -376,3 +398,3 @@

headers: {
Authorization: 'Bearer:asdfasdfasdfasdfasdafd'
Authorization: 'Bearer YOUR_TOKEN_HERE'
}

@@ -396,3 +418,3 @@ }

<details><summary><b>Hooks</b></summary>
### Hooks

@@ -402,7 +424,2 @@ | Hook | Description |

| `useFetch` | The base hook |
| `useGet` | Defaults to a GET request |
| `usePost` | Defaults to a POST request |
| `usePut` | Defaults to a PUT request |
| `usePatch` | Defaults to a PATCH request |
| `useDelete` | Defaults to a DELETE request |
| `useQuery` | For making a GraphQL query |

@@ -414,3 +431,3 @@ | `useMutation` | For making a GraphQL mutation |

<details><summary><b>Options</b></summary>
### Options

@@ -423,47 +440,16 @@ This is exactly what you would pass to the normal js `fetch`, with a little extra.

| `url` | Allows you to set a base path so relative paths can be used for each request :) | empty string |
| `data` | Allows you to set a default value for `data` | `undefined` |
| `loading` | Allows you to set default value for `loading` | `false` unless `onMount === true` |
```jsx
const {
data,
loading,
error,
request,
get,
post,
patch,
put,
delete // don't destructure `delete` though, it's a keyword
del, // <- that's why we have this (del). or use `request.delete`
abort,
query, // GraphQL
mutate, // GraphQL
} = useFetch({
useFetch({
// accepts all `fetch` options such as headers, method, etc.
url: 'https://example.com', // used to be `baseUrl`
onMount: true
onMount: true,
data: [], // default for `data` field
loading: false, // default for `loading` field
})
```
or
```jsx
const [data, loading, error, request] = useFetch({
// accepts all `fetch` options such as headers, method, etc.
url: 'https://example.com', // used to be `baseUrl`
onMount: true
})
const {
get,
post,
patch,
put,
delete // don't destructure `delete` though, it's a keyword
del, // <- that's why we have this (del). or use `request.delete`
abort,
query, // GraphQL
mutate, // GraphQL
} = request
```
</details>
Feature Requests/Ideas

@@ -479,3 +465,4 @@ ----------------------

- [ ] tests for GraphQL hooks `useMutation` + `useQuery`
- [ ] make work with FormData
- [ ] react native support
- [ ] documentation for FormData
- [ ] Make work with React Suspense [current example WIP](https://codesandbox.io/s/7ww5950no0)

@@ -485,3 +472,2 @@ - [ ] get it all working on a SSR codesandbox, this way we can have api to call locally

- [ ] add `timeout`
- [ ] add `debounce`
- [ ] maybe add a `retry: 3` which would specify the amount of times it should retry before erroring out

@@ -492,2 +478,48 @@ - [ ] make GraphQL work with React Suspense

- [ ] show comparison with Apollo
- [ ] Interceptors (potential syntax example) this shows how to get access tokens on each request if an access token or refresh token is expired
```jsx
const App = () => {
const { get } = useFetch('https://example.com')
const [accessToken, setAccessToken] = useLocalStorage('access-token')
const [refreshToken, setRefreshToken] = useLocalStorage('refresh-token')
const { history } = useReactRouter()
const options = {
interceptors: {
async request(opts) {
let headers = {}
// refresh token expires in 1 day, used to get access token
if (!refreshToken || isExpired(refreshToken)) {
return history.push('/login')
}
// access token expires every 15 minutes, use refresh token to get new access token
if (!accessToken || isExpired(accessToken)) {
const access = await get(`/access-token?refreshToken=${refreshToken}`)
setAccessToken(access)
headers = {
Authorization: `Bearer ${access}`,
}
}
const finalOptions = {
...opts,
headers: {
...opts.headers,
...headers,
},
}
return finalOptions
},
},
headers: {
Authorization: `Bearer ${accessToken}`
}
}
return (
<Provider url='https://example.com' options={options}>
<App />
</Provider>
)
}
```
- [ ] Dedupe requests done to the same endpoint. Only one request to the same endpoint will be initiated. [ref](https://www.npmjs.com/package/@bjornagh/use-fetch)
- [ ] Cache responses to improve speed and reduce amount of requests
- [ ] maybe add syntax for inline headers like this

@@ -502,4 +534,25 @@ ```jsx

.get()
```
- [ ] maybe add snake_case -> camelCase option to `<Provider />`. This would
convert all the keys in the response to camelCase.
Not exactly sure how this syntax should look because what
if you want to have this only go 1 layer deep into the response
object. Or if this is just out of scope for this library.
```jsx
<Provider responseKeys={{ case: 'camel' }}><App /></Provider>
```
- [ ] potential syntax `onUpdate`
```jsx
const request = useFetch('url', {
onUpdate: [props.id] // everytime props.id is updated, it will re-run the request GET in this case
})
```
- [ ] see if you can make this work without causing infinite loop when having `request` as a dependency of `useEffect`. I wish the exhaustive dependencies would allow you to do `[request.get]` instead of forcing `[request]`. It doesn't cause infinite loop with `[request.get]` and that's the only method being used inside `useEffect`
- [ ] add callback to completely overwrite options. Let's say you have `<Provider url='url.com' options={{ headers: 'Auth': 'some-token' }}><App /></Provider>`, but for one api call, you don't want that header in your `useFetch` at all for one instance in your app. This would allow you to remove that
```jsx
const request = useFetch('https://url.com', globalOptions => {
delete globalOptions.headers.Authorization
return globalOptions
})
```

@@ -506,0 +559,0 @@ <details><summary><b>The Goal With Suspense <sup><strong>(not implemented yet)</strong></sup></b></summary>

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