Skip to content

Commit

Permalink
fix: add fetchWithTimeout
Browse files Browse the repository at this point in the history
  • Loading branch information
JimmyLv committed Feb 27, 2023
1 parent 396de3d commit e3722dc
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
3 changes: 2 additions & 1 deletion pages/[...slug].tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { useLocalStorage } from "react-use";
import Footer from "../components/Footer";
import Header from "../components/Header";
import SquigglyLines from "../components/SquigglyLines";
import { fetchWithTimeout } from "../utils/fetchWithTimeout";

export const Home: NextPage = () => {
const router = useRouter();
Expand Down Expand Up @@ -49,7 +50,7 @@ export const Home: NextPage = () => {
router.replace(curUrl);
}
setLoading(true);
const response = await fetch("/api/summarize", {
const response = await fetchWithTimeout("/api/summarize", {
method: "POST",
headers: {
"Content-Type": "application/json",
Expand Down
20 changes: 20 additions & 0 deletions utils/fetchWithTimeout.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
interface Options extends RequestInit {
/** timeout, default: 8000ms */
timeout?: number
}

export async function fetchWithTimeout(
resource: RequestInfo | URL,
options: Options = {}
) {
const { timeout } = options

const controller = new AbortController()
const id = setTimeout(() => controller.abort(), timeout)
const response = await fetch(resource, {
...options,
signal: controller.signal
})
clearTimeout(id)
return response
}

1 comment on commit e3722dc

@vercel
Copy link

@vercel vercel bot commented on e3722dc Feb 27, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.