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:
@@ -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("/"));
|
||||
|
||||
37
web/packages/new/photos/components/use-wrap.tsx
Normal file
37
web/packages/new/photos/components/use-wrap.tsx
Normal 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;
|
||||
};
|
||||
Reference in New Issue
Block a user