Skip to content

Build your personal knowledge base with Trilium Notes

client/content manager/space usage: do not refresh automatically, use manual refresh instead

Adorian Dorancdf429fabd8a
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 9898098232..c093f7e6f4 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -2691,6 +2691,7 @@
"load_failed": "Space usage could not be measured",
"view_overview": "Overview",
"view_browse": "Browse",
+ "refresh": "Refresh",
"other_notes_one": "1 other note",
"other_notes_other": "Other {{count}} notes",
"hidden_notes_one": "1 hidden note",
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.spec.tsx
index 2f3d6d4cda..3651fa1153 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.spec.tsx
@@ -20,7 +20,8 @@ const mocks = vi.hoisted(() => ({
failed: false,
fetchedUrls: [] as string[],
donutProps: undefined as unknown,
- openContextMenu: vi.fn()
+ openContextMenu: vi.fn(),
+ contentChanged: vi.fn()
}));
vi.mock("./context_menu", () => ({
@@ -82,7 +83,8 @@ let container: HTMLDivElement | undefined;
function BrowseHost() {
const [ path, setPath ] = useState([ "root" ]);
- return <Browse path={path} onPathChange={setPath} />;
+ // The refresh token never changes here: navigation is what this spec is about.
+ return <Browse path={path} onPathChange={setPath} refreshToken={0} onContentChanged={mocks.contentChanged} />;
}
function renderBrowse() {
@@ -202,10 +204,12 @@ describe("Browse", () => {
const event = new MouseEvent("contextmenu");
const ring = donutProps().outerRings[0];
ring.onSegmentContextMenu?.({ id: "child/child1", value: 40, data: { noteId: "child1" } }, event);
- expect(mocks.openContextMenu).toHaveBeenCalledWith(event, [ "root", "child1" ], expect.any(Function));
+ expect(mocks.openContextMenu).toHaveBeenCalledWith(
+ event, [ "root", "child1" ], expect.any(Function), mocks.contentChanged);
donutProps().onTitleContextMenu(event);
- expect(mocks.openContextMenu).toHaveBeenLastCalledWith(event, [ "root" ], expect.any(Function));
+ expect(mocks.openContextMenu).toHaveBeenLastCalledWith(
+ event, [ "root" ], expect.any(Function), mocks.contentChanged);
// Showing a note's details from within Browse is this view's own descent.
mocks.openContextMenu.mock.calls[0][2]([ "root", "child1" ]);
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.tsx
index d52b200ef5..67f2fa96d5 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.tsx
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/browse.tsx
@@ -9,7 +9,7 @@ import { t } from "../../../../../services/i18n";
import { formatSize } from "../../../../../services/utils";
import ActionButton from "../../../../react/ActionButton";
import type { DonutRing } from "../../../../react/charts/DonutChart";
-import { openSpaceUsageContextMenu } from "./context_menu";
+import { type ContentChangedHandler, openSpaceUsageContextMenu } from "./context_menu";
import { buildChildrenSegments, type UsageSegmentData } from "./donut_segments";
import NoteUsageDonut, { segmentTooltip } from "./note_usage_donut";
import SpaceUsagePlaceholder from "./placeholder";
@@ -22,6 +22,10 @@ interface BrowseProps {
/** Note IDs from the root (inclusive) down to the note in view. */
path: string[];
onPathChange: (path: string[]) => void;
+ /** Changes when the section's refresh button asks for a fresh reading of this note. */
+ refreshToken: number;
+ /** Called once the menu deleted something, so the donut stops drawing what is no longer there. */
+ onContentChanged: ContentChangedHandler;
}
/**
@@ -32,9 +36,10 @@ interface BrowseProps {
* The path is owned by the section rather than the view, so that "Show details" elsewhere in Space
* Usage can drop the user straight onto a note here.
*/
-export default function Browse({ path, onPathChange }: BrowseProps) {
+export default function Browse({ path, onPathChange, refreshToken, onContentChanged }: BrowseProps) {
const noteId = path[path.length - 1];
- const { data: usage, failed } = useSpaceUsageFetch<SpaceUsageNoteResponse>(`space-usage/note/${noteId}`);
+ const { data: usage, failed } = useSpaceUsageFetch<SpaceUsageNoteResponse>(
+ `space-usage/note/${noteId}`, refreshToken);
const titles = useNoteTitles(path, usage);
const getTitle = useCallback((id: string) => titles.get(id) ?? id, [ titles ]);
@@ -62,10 +67,10 @@ export default function Browse({ path, onPathChange }: BrowseProps) {
const childId = segment.data?.noteId;
if (childId) {
- void openSpaceUsageContextMenu(event, [ ...path, childId ], onPathChange);
+ void openSpaceUsageContextMenu(event, [ ...path, childId ], onPathChange, onContentChanged);
}
}
- }), [ usage, getTitle, path, onPathChange ]);
+ }), [ usage, getTitle, path, onPathChange, onContentChanged ]);
return (
<div className="space-usage-browse">
@@ -94,7 +99,8 @@ export default function Browse({ path, onPathChange }: BrowseProps) {
title={getTitle(usage.noteId)}
notePath={path}
outerRings={[ childrenRing ]}
- onTitleContextMenu={(event) => void openSpaceUsageContextMenu(event, path, onPathChange)}
+ onTitleContextMenu={(event) =>
+ void openSpaceUsageContextMenu(event, path, onPathChange, onContentChanged)}
centerActions={
<ActionButton
className="space-usage-back"
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.spec.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.spec.ts
index 0f9e9f8e68..215911df7e 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.spec.ts
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.spec.ts
@@ -13,9 +13,12 @@ const mocks = vi.hoisted(() => ({
branchIds: new Map<string, string>(),
triggerCommand: vi.fn(),
openContextWithNote: vi.fn(),
- deleteNotes: vi.fn(),
+ // Answers like the real one: true when the deletion went through, false when the user backed
+ // out of its confirmation dialog.
+ deleteNotes: vi.fn(async (..._args: unknown[]) => true),
downloadFileNote: vi.fn(),
- showDetails: vi.fn()
+ showDetails: vi.fn(),
+ contentChanged: vi.fn()
}));
vi.mock("../../../../../menus/context_menu", () => ({
@@ -95,7 +98,7 @@ function invoke(icon: string) {
}
function openFor(notePath: string[]) {
- return openSpaceUsageContextMenu(contextMenuEvent(), notePath, mocks.showDetails);
+ return openSpaceUsageContextMenu(contextMenuEvent(), notePath, mocks.showDetails, mocks.contentChanged);
}
afterEach(() => {
@@ -111,7 +114,7 @@ describe("openSpaceUsageContextMenu", () => {
mocks.branchIds.set("p/n1", "b1");
const event = contextMenuEvent();
- await openSpaceUsageContextMenu(event, [ "root", "p", "n1" ], mocks.showDetails);
+ await openSpaceUsageContextMenu(event, [ "root", "p", "n1" ], mocks.showDetails, mocks.contentChanged);
// The chart keeps the pointer, and the browser's own menu stays out of the way.
expect(event.preventDefault).toHaveBeenCalled();
@@ -142,6 +145,23 @@ describe("openSpaceUsageContextMenu", () => {
expect(mocks.deleteNotes).toHaveBeenCalledWith([ "b1" ], false, false);
});
+ it("asks for a fresh reading once a delete goes through, and not when it is called off", async () => {
+ givenNote("n1");
+ mocks.branchIds.set("p/n1", "b1");
+ await openFor([ "root", "p", "n1" ]);
+
+ // The views measure on demand, so the one thing that can outdate them from inside has to
+ // say so — otherwise the deleted note keeps its cell and stays counted in the totals.
+ invoke(DELETE);
+ await vi.waitFor(() => expect(mocks.contentChanged).toHaveBeenCalledTimes(1));
+
+ // Backing out of the confirmation changes nothing, so nothing is re-measured either.
+ mocks.deleteNotes.mockResolvedValueOnce(false);
+ invoke(DELETE);
+ await vi.waitFor(() => expect(mocks.deleteNotes).toHaveBeenCalledTimes(2));
+ expect(mocks.contentChanged).toHaveBeenCalledTimes(1);
+ });
+
it("adds Download for file-bearing types, disabled when the content is away", async () => {
givenNote("f1", "file");
mocks.branchIds.set("p/f1", "b1");
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.ts
index e8c2ba6abe..2d4ca9440b 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.ts
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/context_menu.ts
@@ -14,6 +14,15 @@ const ROOT_NOTE_ID = "root";
/** Switches the section to Browse, focused on the given path. */
export type ShowDetailsHandler = (notePath: string[]) => void;
+/**
+ * Asks the section for a fresh reading, after this menu changed what there is to measure.
+ *
+ * The views take a reading when asked rather than following the database, so an action taken from
+ * within them has to say so — otherwise a note the user just deleted keeps its cell, and the totals
+ * keep counting it.
+ */
+export type ContentChangedHandler = () => void;
+
/**
* The actions every Space Usage view offers on a note it draws — the treemap cells of Overview, the
* children ring and center note of Browse. One builder so a note answers the same way whichever
@@ -27,7 +36,8 @@ export type ShowDetailsHandler = (notePath: string[]) => void;
export async function openSpaceUsageContextMenu(
event: ContextMenuEvent,
notePath: string[],
- onShowDetails: ShowDetailsHandler
+ onShowDetails: ShowDetailsHandler,
+ onContentChanged: ContentChangedHandler
) {
event.preventDefault();
event.stopPropagation();
@@ -98,9 +108,15 @@ export async function openSpaceUsageContextMenu(
uiIcon: "bx bx-trash destructive-action-icon",
enabled: !!branchId,
handler: () => {
- if (branchId) {
- void branches.deleteNotes([ branchId ], false, false);
+ if (!branchId) {
+ return;
}
+
+ // Only once the deletion actually happened: `deleteNotes` answers false when
+ // the user backs out of its confirmation, and re-measuring the whole database
+ // for a cancelled action is exactly what the views avoid doing.
+ void branches.deleteNotes([ branchId ], false, false)
+ .then((deleted) => deleted && onContentChanged());
}
}
])
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.css b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.css
index d6cdaff350..b5932bc5fc 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.css
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.css
@@ -23,6 +23,8 @@
.space-usage-toolbar {
display: flex;
justify-content: flex-end;
+ align-items: center;
+ gap: 0.5em;
}
.space-usage-section {
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsx
index fe5f5c38d2..db86900503 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.spec.tsx
@@ -7,15 +7,25 @@ import { formatSize } from "../../../../../services/utils";
const mocks = vi.hoisted(() => ({
overview: undefined as unknown,
- failed: false
+ failed: false,
+ loading: false,
+ /** The token the section last asked each view to measure at. */
+ overviewToken: undefined as number | undefined,
+ browseToken: undefined as number | undefined
}));
vi.mock("./use_space_usage_fetch", () => ({
- useSpaceUsageFetch: () => ({ data: mocks.overview, failed: mocks.failed })
+ useSpaceUsageFetch: (_url: string, refreshToken: number) => {
+ mocks.overviewToken = refreshToken;
+ return { data: mocks.overview, failed: mocks.failed, loading: mocks.loading };
+ }
}));
vi.mock("./browse", () => ({
- default: () => <div className="browse-stub" />
+ default: ({ refreshToken }: { refreshToken: number }) => {
+ mocks.browseToken = refreshToken;
+ return <div className="browse-stub" />;
+ }
}));
vi.mock("./overview", () => ({
@@ -66,6 +76,9 @@ afterEach(() => {
}
mocks.overview = undefined;
mocks.failed = false;
+ mocks.loading = false;
+ mocks.overviewToken = undefined;
+ mocks.browseToken = undefined;
});
describe("SpaceUsage section", () => {
@@ -113,8 +126,9 @@ describe("SpaceUsage section", () => {
const probe = renderSection();
// Labels depend on the (uninitialized) test i18n; the inactive button is the other view.
+ // Scoped to the view group so the refresh button beside it is never mistaken for one.
const inactiveViewButton = () =>
- [ ...probe.querySelectorAll<HTMLButtonElement>(".header-stub button") ]
+ [ ...probe.querySelectorAll<HTMLButtonElement>(".content-manager-view-choice button") ]
.find((button) => !button.classList.contains("active"));
inactiveViewButton()?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
@@ -130,4 +144,34 @@ describe("SpaceUsage section", () => {
expect(probe.querySelector(".browse-stub")).toBeNull();
expect(probe.querySelector(".space-usage-status")).not.toBeNull();
});
+
+ it("asks both views for a fresh reading when refresh is pressed, and only then", async () => {
+ mocks.overview = OVERVIEW;
+ const probe = renderSection();
+ const refresh = () => probe.querySelector<HTMLButtonElement>(".space-usage-refresh");
+
+ const initialToken = mocks.overviewToken ?? 0;
+
+ // Switching views re-renders everything below; measuring must not restart because of it —
+ // it is far too expensive to repeat whenever something on the page happens to change.
+ [ ...probe.querySelectorAll<HTMLButtonElement>(".content-manager-view-choice button") ][1]
+ ?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await flushRender();
+ expect(mocks.overviewToken).toBe(initialToken);
+ expect(mocks.browseToken).toBe(initialToken);
+
+ refresh()?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await flushRender();
+
+ // Browse measures a different endpoint, so it needs the same signal to follow along.
+ expect(mocks.overviewToken).toBe(initialToken + 1);
+ expect(mocks.browseToken).toBe(initialToken + 1);
+ });
+
+ it("keeps the refresh button out while a reading is being taken", () => {
+ mocks.overview = OVERVIEW;
+ mocks.loading = true;
+
+ expect(renderSection().querySelector<HTMLButtonElement>(".space-usage-refresh")?.disabled).toBe(true);
+ });
});
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.tsx
index 4437dcda82..d3f352044a 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.tsx
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/index.tsx
@@ -5,6 +5,7 @@ import { useCallback, useMemo, useRef, useState } from "preact/hooks";
import { t } from "../../../../../services/i18n";
import { formatSize } from "../../../../../services/utils";
+import ActionButton from "../../../../react/ActionButton";
import { useStaticTooltip } from "../../../../react/hooks";
import SegmentedChoice from "../../../../react/SegmentedChoice";
import OptionsPageHeader from "../../components/OptionsPageHeader";
@@ -21,6 +22,12 @@ type SpaceUsageView = "overview" | "browse";
export default function SpaceUsage({ sectionSwitcher }: ContentManagerSectionProps) {
const [ view, setView ] = useState<SpaceUsageView>("overview");
+ // Bumped by the refresh button. Both views read it, so one press re-measures whatever is on
+ // screen; a number rather than a callback, which would change identity on every render here and
+ // have the views re-measuring the database continuously.
+ const [ refreshToken, setRefreshToken ] = useState(0);
+ // Stable, so handing it to the views costs them nothing on re-render.
+ const refresh = useCallback(() => setRefreshToken((token) => token + 1), []);
// Browse's position lives here so that "Show details", offered on any note either view draws,
// can land the user on that note — switching the view along the way when it comes from Overview.
const [ browsePath, setBrowsePath ] = useState([ "root" ]);
@@ -31,8 +38,8 @@ export default function SpaceUsage({ sectionSwitcher }: ContentManagerSectionPro
// Kept fetched across both views so returning to the treemap draws immediately rather than
// blanking. Revisions stay out of the ranking so it shares the basis of the areas the treemap
// draws — asking for one basis and drawing the other would rank in notes the cells then shrink.
- const { data: overview, failed } = useSpaceUsageFetch<SpaceUsageOverviewResponse>(
- `space-usage/overview?limit=${OVERVIEW_LIMIT}`);
+ const { data: overview, failed, loading } = useSpaceUsageFetch<SpaceUsageOverviewResponse>(
+ `space-usage/overview?limit=${OVERVIEW_LIMIT}`, refreshToken);
return (
<div className="space-usage-section">
@@ -44,12 +51,28 @@ export default function SpaceUsage({ sectionSwitcher }: ContentManagerSectionPro
currentValue={view}
onChange={setView}
/>
+ {/* Measuring is expensive, so a reading is taken when asked for rather than
+ kept live — and the button stays out while one is being taken. */}
+ <ActionButton
+ className="space-usage-refresh"
+ icon="bx bx-refresh"
+ text={t("space_usage.refresh")}
+ disabled={loading}
+ onClick={refresh}
+ />
</div>
} />
- {view === "browse" && <Browse path={browsePath} onPathChange={setBrowsePath} />}
+ {view === "browse" && (
+ <Browse
+ path={browsePath}
+ onPathChange={setBrowsePath}
+ refreshToken={refreshToken}
+ onContentChanged={refresh}
+ />
+ )}
{view === "overview" && (overview
- ? <Overview overview={overview} onShowDetails={showDetails} />
+ ? <Overview overview={overview} onShowDetails={showDetails} onContentChanged={refresh} />
: <SpaceUsagePlaceholder failed={failed} />)}
{/* Overview only: these are whole-database totals, and beside a single note's donut
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.spec.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.spec.tsx
index 4dec093760..8fbe47b55f 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.spec.tsx
@@ -5,7 +5,8 @@ import { afterEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({
triggerCommand: vi.fn(),
openContextMenu: vi.fn(),
- showDetails: vi.fn()
+ showDetails: vi.fn(),
+ contentChanged: vi.fn()
}));
vi.mock("../../../../../components/app_context", () => ({
@@ -48,7 +49,14 @@ let container: HTMLDivElement | undefined;
function renderOverview() {
container = document.body.appendChild(document.createElement("div"));
- render(<Overview overview={OVERVIEW} onShowDetails={mocks.showDetails} />, container);
+ render(
+ <Overview
+ overview={OVERVIEW}
+ onShowDetails={mocks.showDetails}
+ onContentChanged={mocks.contentChanged}
+ />,
+ container
+ );
return container;
}
@@ -97,7 +105,7 @@ describe("Overview", () => {
cell?.dispatchEvent(new MouseEvent("contextmenu", { bubbles: true }));
expect(mocks.openContextMenu).toHaveBeenCalledWith(
- expect.anything(), [ "root", "n1" ], mocks.showDetails);
+ expect.anything(), [ "root", "n1" ], mocks.showDetails, mocks.contentChanged);
mocks.triggerCommand.mockClear();
mocks.openContextMenu.mockClear();
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.tsx b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.tsx
index 243298fc78..170c4b3005 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.tsx
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/overview.tsx
@@ -5,7 +5,12 @@ import froca from "../../../../../services/froca";
import { t } from "../../../../../services/i18n";
import { formatSize } from "../../../../../services/utils";
import Treemap, { type TreemapItem } from "../../../../react/charts/Treemap";
-import { openSpaceUsageContextMenu, quickEditNote, type ShowDetailsHandler } from "./context_menu";
+import {
+ type ContentChangedHandler,
+ openSpaceUsageContextMenu,
+ quickEditNote,
+ type ShowDetailsHandler
+} from "./context_menu";
import { bucketWeight, buildOverviewModel, type OverviewCell } from "./overview_model";
/**
@@ -19,10 +24,12 @@ const INCLUDE_REVISIONS = false;
interface OverviewProps {
overview: SpaceUsageOverviewResponse;
onShowDetails: ShowDetailsHandler;
+ /** Called once the menu deleted something, so the map stops drawing what is no longer there. */
+ onContentChanged: ContentChangedHandler;
}
/** The treemap over the whole database: every large note at its tree location. */
-export default function Overview({ overview, onShowDetails }: OverviewProps) {
+export default function Overview({ overview, onShowDetails, onContentChanged }: OverviewProps) {
const icons = useNoteIcons(overview);
// The labels are formatted here rather than in the model, which stays free of i18n: a bucket
@@ -61,7 +68,7 @@ export default function Overview({ overview, onShowDetails }: OverviewProps) {
root={model}
onItemClick={(item) => withCellPath(item, quickEditNote)}
onItemContextMenu={(item, event) => withCellPath(item, (notePath) =>
- void openSpaceUsageContextMenu(event, notePath, onShowDetails))}
+ void openSpaceUsageContextMenu(event, notePath, onShowDetails, onContentChanged))}
/>
</div>
);
diff --git a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.ts b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.ts
index f0541cb1ff..be3ed65b3b 100644
--- a/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.ts
+++ b/apps/client/src/widgets/type_widgets/options/content_manager/space_usage/use_space_usage_fetch.ts
@@ -6,10 +6,13 @@ export interface SpaceUsageFetch<T> {
data: T | null;
/** The last attempt failed. Meaningful only while {@link data} is still null — see below. */
failed: boolean;
+ /** A request is in flight. Measuring is expensive enough to be worth keeping to one at a time. */
+ loading: boolean;
}
/**
- * Fetches a space-usage endpoint once, and again whenever the URL changes (Browse navigation).
+ * Fetches a space-usage endpoint once, and again whenever the URL changes (Browse navigation) or
+ * {@link refreshToken} does — which is how the page's refresh button asks for a fresh reading.
*
* Deliberately *not* refreshed when notes change: measuring the database is expensive enough that
* re-running it after every edit would keep the server busy for as long as this page stayed open —
@@ -24,13 +27,15 @@ export interface SpaceUsageFetch<T> {
* connection, an unreachable server), which would leave no trace at all. Callers show the failure
* only while `data` is null — once a payload exists, keeping it beats blanking the charts.
*/
-export function useSpaceUsageFetch<T>(url: string): SpaceUsageFetch<T> {
+export function useSpaceUsageFetch<T>(url: string, refreshToken = 0): SpaceUsageFetch<T> {
const [ data, setData ] = useState<T | null>(null);
const [ failed, setFailed ] = useState(false);
+ const [ loading, setLoading ] = useState(true);
const latestRequest = useRef(0);
const refresh = useCallback(async () => {
const requestId = ++latestRequest.current;
+ setLoading(true);
try {
const response = await server.get<T>(url);
@@ -45,10 +50,18 @@ export function useSpaceUsageFetch<T>(url: string): SpaceUsageFetch<T> {
if (requestId === latestRequest.current) {
setFailed(true);
}
+ } finally {
+ if (requestId === latestRequest.current) {
+ setLoading(false);
+ }
}
- }, [ url ]);
+ // A plain number rather than a callback the caller hands down: a function would carry a new
+ // identity on every render of the page above, and re-measure the whole database each time
+ // anything there changed.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [ url, refreshToken ]);
useEffect(() => { void refresh(); }, [ refresh ]);
- return { data, failed };
+ return { data, failed, loading };
}