diff --git a/src/components/profile/profile-item.tsx b/src/components/profile/profile-item.tsx index 0fd587f..e42acc4 100644 --- a/src/components/profile/profile-item.tsx +++ b/src/components/profile/profile-item.tsx @@ -1,4 +1,4 @@ -import React, { useRef, useState } from "react"; +import React, { useState } from "react"; import dayjs from "dayjs"; import { alpha, @@ -11,6 +11,7 @@ import { MenuItem, Menu, } from "@mui/material"; +import { useLockFn } from "ahooks"; import { useSWRConfig } from "swr"; import { RefreshRounded } from "@mui/icons-material"; import { CmdType } from "../../services/types"; @@ -93,20 +94,16 @@ const ProfileItem: React.FC = (props) => { } }; - const deleteRef = useRef(false); - const onDelete = async () => { + const onDelete = useLockFn(async () => { setAnchorEl(null); - if (deleteRef.current) return; - deleteRef.current = true; + try { await deleteProfile(index); mutate("getProfiles"); } catch (err: any) { Notice.error(err.toString()); - } finally { - deleteRef.current = false; } - }; + }); const handleContextMenu = ( event: React.MouseEvent diff --git a/src/pages/profiles.tsx b/src/pages/profiles.tsx index 4996df2..802e34c 100644 --- a/src/pages/profiles.tsx +++ b/src/pages/profiles.tsx @@ -1,5 +1,6 @@ import useSWR, { useSWRConfig } from "swr"; -import { useEffect, useRef, useState } from "react"; +import { useEffect, useState } from "react"; +import { useLockFn } from "ahooks"; import { Box, Button, Grid, TextField } from "@mui/material"; import { getProfiles, @@ -81,37 +82,27 @@ const ProfilePage = () => { } }; - const lockRef = useRef(false); - const onSelect = async (index: number, force: boolean) => { - if (lockRef.current) return; + const onSelect = useLockFn(async (index: number, force: boolean) => { if (!force && index === profiles.current) return; - lockRef.current = true; + try { await selectProfile(index); mutate("getProfiles", { ...profiles, current: index }, true); } catch (err: any) { err && Notice.error(err.toString()); - } finally { - lockRef.current = false; } - }; + }); - const lockNewRef = useRef(false); const [dialogOpen, setDialogOpen] = useState(false); - const onNew = async (name: string, desc: string) => { - if (lockNewRef.current) return; - lockNewRef.current = true; - + const onNew = useLockFn(async (name: string, desc: string) => { try { await newProfile(name, desc); setDialogOpen(false); mutate("getProfiles"); } catch (err: any) { err && Notice.error(err.toString()); - } finally { - lockNewRef.current = false; } - }; + }); return (