-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Rod Lewis
committed
Jan 5, 2023
0 parents
commit 498697a
Showing
22 changed files
with
669 additions
and
0 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,24 @@ | ||
# Logs | ||
logs | ||
*.log | ||
npm-debug.log* | ||
yarn-debug.log* | ||
yarn-error.log* | ||
pnpm-debug.log* | ||
lerna-debug.log* | ||
|
||
node_modules | ||
*.local | ||
|
||
# Editor directories and files | ||
__tests__ | ||
.vscode/* | ||
!.vscode/extensions.json | ||
.idea | ||
.DS_Store | ||
*.yaml | ||
*.suo | ||
*.ntvs* | ||
*.njsproj | ||
*.sln | ||
*.sw? |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,21 @@ | ||
MIT License | ||
|
||
Copyright (c) 2022 Rod Lewis | ||
|
||
Permission is hereby granted, free of charge, to any person obtaining a copy | ||
of this software and associated documentation files (the "Software"), to deal | ||
in the Software without restriction, including without limitation the rights | ||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
copies of the Software, and to permit persons to whom the Software is | ||
furnished to do so, subject to the following conditions: | ||
|
||
The above copyright notice and this permission notice shall be included in all | ||
copies or substantial portions of the Software. | ||
|
||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
SOFTWARE. |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,136 @@ | ||
<div align="center"><img src="https://user-images.githubusercontent.com/20704726/176831638-a5c27908-365e-4edc-aac8-c7073fc18dfb.png" width="200" alt="usdh logo"/> <h1>useData hook</h1></div> | ||
|
||
### install | ||
|
||
yarn add usdh | ||
|
||
or | ||
|
||
pnpm add usdh | ||
|
||
|
||
|
||
or | ||
|
||
npm install usdh | ||
|
||
|
||
|
||
### import | ||
|
||
import { useData } from "usdh" | ||
|
||
## useData | ||
useData is the main React hook of usdh. | ||
useData performs a fetch request and returns the data, loading state and error. It will also cache the data for a specified amount of time using the cacheKey or url if no cacheKey is specified. You can also specify optimisticData which will be returned while the data is loading. This is useful for displaying data immediately while the fetch request is being performed. Typically you would use this for data that is not critical to the user experience. For example, if you are displaying a list of todos, you could use optimisticData to display the todos immediately while the fetch request is being performed. If the fetch request fails, the error will be returned and the optimisticData will be removed. | ||
|
||
### examples | ||
#### basic | ||
|
||
import { useData } from "usdh" | ||
|
||
const App = () => { | ||
const { data, loading, error } = useData({ | ||
url: "https://jsonplaceholder.typicode.com/todos/1" | ||
}) | ||
|
||
if (loading) return <p>Loading...</p> | ||
if (error) return <p>Error: {error.message}</p> | ||
|
||
return ( | ||
<div> | ||
<h1>{data.title}</h1> | ||
<p>{data.completed ? "Completed" : "Not completed"}</p> | ||
</div> | ||
) | ||
} | ||
#### with optimisticData | ||
|
||
import { useData } from "usdh" | ||
|
||
const App = () => { | ||
const { data, loading, error } = useData({ | ||
url: "https://jsonplaceholder.typicode.com/todos/1", | ||
optimisticData: { | ||
title: "My todo", | ||
completed: false | ||
}, | ||
} | ||
}) | ||
|
||
if (loading) return <p>Loading...</p> | ||
if (error) return <p>Error: {error.message}</p> | ||
|
||
return ( | ||
<div> | ||
<h1>{data.title}</h1> | ||
<p>{data.completed ? "Completed" : "Not completed"}</p> | ||
</div> | ||
) | ||
} | ||
|
||
#### with cacheKey and cacheTime | ||
|
||
import { useData } from "usdh" | ||
const App = () => { | ||
const { data, loading, error } = useData({ | ||
url: "https://jsonplaceholder.typicode.com/todos/1", | ||
cacheKey: "my-todo", | ||
cacheTime: 1000 * 60 * 60 * 24 // 1 day | ||
}) | ||
if (loading) return <p>Loading...</p> | ||
if (error) return <p>Error: {error.message}</p> | ||
return ( | ||
<div> | ||
<h1>{data.title}</h1> | ||
<p>{data.completed ? "Completed" : "Not completed"}</p> | ||
</div> | ||
) | ||
} | ||
#### with init | ||
|
||
import { useData } from "usdh" | ||
|
||
const App = () => { | ||
const { data, loading, error } = useData({ | ||
url: "https://jsonplaceholder.typicode.com/todos/1", | ||
init: { | ||
method: "POST", | ||
body: JSON.stringify({ | ||
title: "My todo", | ||
completed: true | ||
}) | ||
} | ||
}) | ||
|
||
if (loading) return <p>Loading...</p> | ||
if (error) return <p>Error: {error.message}</p> | ||
|
||
return ( | ||
<div> | ||
<h1>{data.title}</h1> | ||
<p>{data.completed ? "Completed" : "Not completed"}</p> | ||
</div> | ||
) | ||
} | ||
|
||
#### with retries | ||
const App = () => { | ||
const { data, loading, error } = useData({ | ||
url: "https://jsonplaceholder.typicode.com/todos/1", | ||
retry: 3 | ||
}) | ||
|
||
if (loading) return <p>Loading...</p> | ||
if (error) return <p>Error: {error.message}</p> | ||
|
||
return ( | ||
<div> | ||
<h1>{data.title}</h1> | ||
<p>{data.completed ? "Completed" : "Not completed"}</p> | ||
</div> | ||
) | ||
} |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,20 @@ | ||
import { useState as a, useEffect as k } from "react"; | ||
function h(r, s) { | ||
const [l, n] = a(null), [d, f] = a(null), [i, o] = a(!0); | ||
return k(() => { | ||
let t; | ||
return typeof Worker < "u" && (t = new Worker("/worker.js?worker&inline")), t ? (t.postMessage({ url: r, init: s }), t.onmessage = (e) => { | ||
const { data: u, error: c } = e.data; | ||
c ? f(c) : n(u), o(!1); | ||
}) : fetch(r, s).then((e) => e.json()).then((e) => { | ||
n(e), o(!1); | ||
}).catch((e) => { | ||
f(e), o(!1); | ||
}), () => { | ||
t && t.terminate(); | ||
}; | ||
}, [r]), { data: l, error: d, loading: i }; | ||
} | ||
export { | ||
h as default | ||
}; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './lib/index' |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
declare function useBackgroundFetch(url: string, init?: RequestInit): { | ||
data: any; | ||
error: any; | ||
loading: boolean; | ||
}; | ||
export default useBackgroundFetch; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
declare type DataHookResult<T> = { | ||
data: T | null; | ||
loading: boolean; | ||
error: Error | null; | ||
}; | ||
declare type UseDataHookProps<T> = { | ||
url: string; | ||
init?: RequestInit; | ||
optimisticData?: T; | ||
useStaleCache?: boolean; | ||
retry?: number; | ||
onError?: (error: Error) => void; | ||
invalidateCache?: boolean; | ||
cacheKey?: string; | ||
expiration?: number; | ||
errorHandlers?: Record<number, (error: Error) => void>; | ||
}; | ||
declare function useData<T>({ url, init, optimisticData, useStaleCache, retry, onError, invalidateCache, cacheKey, expiration, errorHandlers, }: UseDataHookProps<T>): DataHookResult<T>; | ||
export default useData; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
export declare const useBackgroundFetch: Promise<typeof import("./hooks/useBackgroundFetch")>; | ||
export declare const useData: Promise<typeof import("./hooks/useData")>; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
const t = import("./index-9c0312ab.mjs"), o = import("./useData-671558ca.mjs"); | ||
export { | ||
t as useBackgroundFetch, | ||
o as useData | ||
}; |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,81 @@ | ||
import { useState as f, useRef as j, useCallback as L, useEffect as k } from "react"; | ||
function z({ | ||
url: r, | ||
init: i, | ||
optimisticData: C, | ||
useStaleCache: b, | ||
retry: y = 0, | ||
onError: s, | ||
invalidateCache: w = !1, | ||
cacheKey: c = r, | ||
expiration: n, | ||
errorHandlers: a | ||
}) { | ||
const [q, d] = f(C || null), [E, g] = f(!0), [$, D] = f(null), [h, x] = f(y), R = j(), l = j(new AbortController()), T = L(async () => { | ||
C && g(!1); | ||
try { | ||
const e = await caches.open("usdh-cache"), m = await e.match(c); | ||
if (m && !w) { | ||
let t = 0; | ||
if (n) | ||
t = Date.now() + n * 1e3; | ||
else { | ||
const u = m.headers.get("Cache-Control"); | ||
if (console.log("trying"), u) { | ||
console.log("trying cache"); | ||
const p = u.split("max-age=")[1]; | ||
p && (t = Date.now() + Number(p) * 1e3); | ||
} | ||
} | ||
if ((t > Date.now() || b) && (d(await m.json()), g(!1), !b)) | ||
return; | ||
} | ||
const o = await fetch(r, { | ||
...i, | ||
signal: l.current.signal | ||
}); | ||
if (o.ok) { | ||
const t = o.headers.get("Cache-Control"); | ||
if (t || n) { | ||
const u = new Request(c); | ||
e.put(u, o.clone(), { | ||
expiration: n || t | ||
}); | ||
} | ||
d(await o.json()); | ||
} else { | ||
const t = new Error( | ||
`Error ${o.status}: ${o.statusText}` | ||
); | ||
s && s(t), a && a[o.status] && a[o.status](t), D(t), A(); | ||
} | ||
} catch (e) { | ||
s && e instanceof Error && (s(e), A()), e instanceof Error && D(e); | ||
} finally { | ||
g(!1); | ||
} | ||
}, [ | ||
r, | ||
w, | ||
c, | ||
n, | ||
i, | ||
a, | ||
s | ||
]); | ||
function A() { | ||
if (h > 0) { | ||
l.current = new AbortController(); | ||
const e = 2 ** (y - h + 1) * 1e3; | ||
x(h - 1), R.current = setTimeout(() => T(), e); | ||
} | ||
} | ||
return k(() => (l.current = new AbortController(), () => { | ||
l.current.abort(); | ||
}), []), k(() => (T(), () => { | ||
clearTimeout(R.current); | ||
}), [r, w, c, n, i]), { data: q, loading: E, error: $ }; | ||
} | ||
export { | ||
z as default | ||
}; |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
/// <reference types="vite/client" /> |
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,53 @@ | ||
{ | ||
"name": "usdh", | ||
"author": "Rod Lewis", | ||
"description": "useData Hook for Cache API", | ||
"version": "1.0.7", | ||
"license": "MIT", | ||
"repository": { | ||
"type": "git", | ||
"url": "https://github.com/StudentOfJS/usdh.git" | ||
}, | ||
"keywords": [ | ||
"typescript", | ||
"react", | ||
"cache api", | ||
"hook", | ||
"fetch" | ||
], | ||
"scripts": { | ||
"dev": "vite", | ||
"build": "tsc && vite build", | ||
"preview": "vite preview", | ||
"prepack": "json -f package.json -I -e \"delete this.devDependencies;\"", | ||
"test": "vitest --config ./vitest.config.ts", | ||
"coverage": "vitest run --coverage" | ||
}, | ||
"files": [ | ||
"dist" | ||
], | ||
"main": "./dist/usdh.umd.js", | ||
"module": "./dist/usdh.es.js", | ||
"types": "./dist/index.d.ts", | ||
"exports": { | ||
".": { | ||
"import": "./dist/usdh.es.js", | ||
"require": "./dist/usdh.umd.js" | ||
} | ||
}, | ||
"devDependencies": { | ||
"@types/node": "^18.0.0", | ||
"@types/react": "^18.0.14", | ||
"@vitejs/plugin-react": "^3.0.1", | ||
"happy-dom": "^8.1.1", | ||
"json": "^11.0.0", | ||
"react": "^18.2.0", | ||
"typescript": "^4.9.4", | ||
"vite": "^4.0.4", | ||
"vite-plugin-dts": "^1.2.0", | ||
"vitest": "^0.26.3" | ||
}, | ||
"peerDependencies": { | ||
"react": ">=16.8.0" | ||
} | ||
} |
Oops, something went wrong.