From 58ab342c47c268b303be27ff7bec22b37981b3a0 Mon Sep 17 00:00:00 2001 From: Xiao Yijun Date: Tue, 29 Mar 2022 12:58:53 +0800 Subject: [PATCH] refactor(console): the submit state of forms (#455) --- .../src/pages/ApiResourceDetails/index.tsx | 30 +++++++++---------- .../components/CreateForm/index.tsx | 24 +++++++-------- .../src/pages/ApplicationDetails/index.tsx | 28 ++++++++--------- .../components/CreateForm/index.tsx | 25 ++++++---------- .../components/ResetPasswordForm.tsx | 24 +++++++-------- .../console/src/pages/UserDetails/index.tsx | 25 ++++++++-------- .../Users/components/CreateForm/index.tsx | 24 +++++++-------- packages/phrases/src/locales/en.ts | 1 + packages/phrases/src/locales/zh-cn.ts | 1 + 9 files changed, 84 insertions(+), 98 deletions(-) diff --git a/packages/console/src/pages/ApiResourceDetails/index.tsx b/packages/console/src/pages/ApiResourceDetails/index.tsx index ded55d592..50df320ed 100644 --- a/packages/console/src/pages/ApiResourceDetails/index.tsx +++ b/packages/console/src/pages/ApiResourceDetails/index.tsx @@ -1,6 +1,7 @@ import { Resource } from '@logto/schemas'; import React, { useEffect, useState } from 'react'; import { useForm } from 'react-hook-form'; +import { toast } from 'react-hot-toast'; import { useTranslation } from 'react-i18next'; import Modal from 'react-modal'; import { useLocation, useParams } from 'react-router-dom'; @@ -37,10 +38,15 @@ const ApiResourceDetails = () => { const { data, error, mutate } = useSWR(id && `/api/resources/${id}`); const isLoading = !data && !error; - const { handleSubmit, register, reset } = useForm({ + const { + handleSubmit, + register, + reset, + formState: { isSubmitting }, + } = useForm({ defaultValues: data, }); - const [submitting, setSubmitting] = useState(false); + const api = useApi(); const [isDeleteFormOpen, setIsDeleteFormOpen] = useState(false); @@ -54,21 +60,15 @@ const ApiResourceDetails = () => { }, [data, reset]); const onSubmit = handleSubmit(async (formData) => { - if (!data || submitting) { + if (!data || isSubmitting) { return; } - setSubmitting(true); - try { - const updatedApiResource = await api - .patch(`/api/resources/${data.id}`, { json: formData }) - .json(); - void mutate(updatedApiResource); - } catch (error: unknown) { - console.error(error); - } finally { - setSubmitting(false); - } + const updatedApiResource = await api + .patch(`/api/resources/${data.id}`, { json: formData }) + .json(); + void mutate(updatedApiResource); + toast.success(t('api_resource_details.save_success')); }); return ( @@ -157,7 +157,7 @@ const ApiResourceDetails = () => {