Start at attempting to abstract wrap

This can be done much better in many small ways, for now just attempting a
start.
This commit is contained in:
Manav Rathi
2024-09-26 14:30:55 +05:30
parent 7634ba0dea
commit dbd160c135
2 changed files with 54 additions and 7 deletions

View File

@@ -47,7 +47,14 @@ import isElectron from "is-electron";
import type { AppProps } from "next/app";
import { useRouter } from "next/router";
import "photoswipe/dist/photoswipe.css";
import { createContext, useContext, useEffect, useRef, useState } from "react";
import {
createContext,
useCallback,
useContext,
useEffect,
useRef,
useState,
} from "react";
import LoadingBar from "react-top-loading-bar";
import { resumeExportsIfNeeded } from "services/export";
import { photosLogout } from "services/logout";
@@ -269,12 +276,15 @@ export default function App({ Component, pageProps }: AppProps) {
const closeMessageDialog = () => setMessageDialogView(false);
const closeDialogBoxV2 = () => setDialogBoxV2View(false);
const somethingWentWrong = () =>
setDialogMessage({
title: t("error"),
close: { variant: "critical" },
content: t("UNKNOWN_ERROR"),
});
const somethingWentWrong = useCallback(
() =>
setDialogMessage({
title: t("error"),
close: { variant: "critical" },
content: t("UNKNOWN_ERROR"),
}),
[setDialogMessage],
);
const logout = () => {
void photosLogout().then(() => router.push("/"));

View File

@@ -0,0 +1,37 @@
import log from "@/base/log";
import React from "react";
import type { NewAppContextPhotos } from "../types/context";
/**
* Return a wrap function.
*
* This wrap function itself takes an async function, and returns new
* function by wrapping an async function in an error handler, showing the
* global loading bar when the function runs.
*/
export const useWrapAsyncOperation = (
/** See: [Note: Migrating components that need the app context]. */
appContext: NewAppContextPhotos,
) => {
const { startLoading, finishLoading, somethingWentWrong } = appContext;
const wrap = React.useCallback(
(f: () => Promise<void>) => {
const wrapped = async () => {
startLoading();
try {
await f();
} catch (e) {
log.error("Error", e);
somethingWentWrong();
} finally {
finishLoading();
}
};
return (): void => void wrapped();
},
[somethingWentWrong, startLoading, finishLoading],
);
return wrap;
};