Fix: user impersonation switch showing the wrong value (#6126)

* fix: remove register method because ref is not forwarded

* fix: prefetch user to get the correct value for the switch component

* feat: add optimistic update

* feat: disable update button if not dirty

Co-authored-by: Peer Richelsen <peeroke@gmail.com>
Co-authored-by: kodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
Co-authored-by: Joe Au-Yeung <65426560+joeauyeung@users.noreply.github.com>
pull/6139/head
Nafees Nazik 2022-12-21 04:43:31 +05:30 committed by GitHub
parent 7a6349b4c0
commit 3b74717591
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 24 additions and 7 deletions

View File

@ -23,8 +23,24 @@ const ProfileImpersonationView = () => {
const mutation = trpc.viewer.updateProfile.useMutation({
onSuccess: () => {
showToast(t("profile_updated_successfully"), "success");
reset(getValues());
},
onError: (error) => {
onSettled: () => {
utils.viewer.me.invalidate();
},
onMutate: async ({ disableImpersonation }) => {
await utils.viewer.me.cancel();
const previousValue = utils.viewer.me.getData();
if (previousValue && disableImpersonation) {
utils.viewer.me.setData(undefined, { ...previousValue, disableImpersonation });
}
return { previousValue };
},
onError: (error, variables, context) => {
if (context?.previousValue) {
utils.viewer.me.setData(undefined, context.previousValue);
}
showToast(`${t("error")}, ${error.message}`, "error");
},
});
@ -36,10 +52,13 @@ const ProfileImpersonationView = () => {
});
const {
formState: { isSubmitting },
formState: { isSubmitting, isDirty },
setValue,
reset,
getValues,
} = formMethods;
const isDisabled = isSubmitting || !isDirty;
return (
<>
<Meta title={t("impersonation")} description={t("impersonation_description")} />
@ -47,14 +66,12 @@ const ProfileImpersonationView = () => {
form={formMethods}
handleSubmit={({ disableImpersonation }) => {
mutation.mutate({ disableImpersonation });
utils.viewer.me.invalidate();
}}>
<div className="flex space-x-3">
<Switch
{...formMethods.register("disableImpersonation")}
defaultChecked={!user?.disableImpersonation}
onCheckedChange={(e) => {
setValue("disableImpersonation", !e);
setValue("disableImpersonation", !e, { shouldDirty: true });
}}
fitToHeight={true}
/>
@ -67,7 +84,7 @@ const ProfileImpersonationView = () => {
</Skeleton>
</div>
</div>
<Button color="primary" className="mt-8" type="submit" disabled={isSubmitting || mutation.isLoading}>
<Button color="primary" className="mt-8" type="submit" disabled={isDisabled}>
{t("update")}
</Button>
</Form>
@ -79,7 +96,7 @@ ProfileImpersonationView.getLayout = getLayout;
export const getServerSideProps = async (context: GetServerSidePropsContext) => {
const ssr = await ssrInit(context);
await ssr.viewer.me.prefetch();
return {
props: {
trpcState: ssr.dehydrate(),