Skip to content

Commit a520622

Browse files
committed
refactor: useNetworkBusy hook
1 parent a8102af commit a520622

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

app/hooks/useNetworkBusy.ts

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
import { useFetchers, useNavigation } from "react-router";
2+
3+
/**
4+
* Check if any network request is in progress.
5+
*
6+
* This is useful for loading indicators or disabling buttons while a request is being made.
7+
*
8+
* @returns `true` if any network request is in progress, `false` otherwise.
9+
*/
10+
export const useNetworkBusy = () => {
11+
const navigation = useNavigation();
12+
const fetcher = useFetchers();
13+
14+
return navigation.state !== "idle" || fetcher.some((f) => f.state !== "idle");
15+
};

app/routes/_index.tsx

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import { parseWithZod } from "@conform-to/zod";
22
import { Anchor, Card, Container, Divider, Group, Stack } from "@mantine/core";
3-
import { data, Link, redirect, useNavigation } from "react-router";
3+
import { data, Link, redirect } from "react-router";
44
import { getQuery, withQuery } from "ufo";
55

66
import Fa6SolidMagnifyingGlass from "~icons/fa6-solid/magnifying-glass";
@@ -14,6 +14,7 @@ import {
1414
searchApiV1DataSearchGet,
1515
} from "../generated/api/client";
1616
import type { SearchedNote, Topic } from "../generated/api/schemas";
17+
import { useNetworkBusy } from "../hooks/useNetworkBusy";
1718
import type { Route } from "./+types/_index";
1819

1920
export const meta: Route.MetaFunction = () => {
@@ -88,7 +89,7 @@ export default function Index({
8889
actionData,
8990
loaderData,
9091
}: Route.ComponentProps) {
91-
const isLoadingSearchResults = useNavigation().state !== "idle";
92+
const isNetworkBusy = useNetworkBusy();
9293

9394
const {
9495
topics,
@@ -127,7 +128,7 @@ export default function Index({
127128
<SearchPagination
128129
className="ms-auto me-0"
129130
currentQuery={searchQuery}
130-
loading={isLoadingSearchResults}
131+
loading={isNetworkBusy}
131132
meta={paginationMeta}
132133
visibleItemCount={notes.length}
133134
/>
@@ -144,7 +145,7 @@ export default function Index({
144145
<SearchPagination
145146
className="ms-auto me-0"
146147
currentQuery={searchQuery}
147-
loading={isLoadingSearchResults}
148+
loading={isNetworkBusy}
148149
meta={paginationMeta}
149150
visibleItemCount={notes.length}
150151
/>

0 commit comments

Comments
 (0)