Browse Source

ref(ui): Use object style arguments with react query (#77047)

Scott Cooper 6 months ago
parent
commit
6472652931

+ 3 - 1
static/app/actionCreators/events.tsx

@@ -298,7 +298,9 @@ export const useDeleteEventAttachmentOptimistic = (
       );
     },
     onMutate: async variables => {
-      await queryClient.cancelQueries(makeFetchEventAttachmentsQueryKey(variables));
+      await queryClient.cancelQueries({
+        queryKey: makeFetchEventAttachmentsQueryKey(variables),
+      });
 
       const previous = getApiQueryData<FetchEventAttachmentResponse>(
         queryClient,

+ 4 - 4
static/app/components/dynamicSampling/investigationRule.tsx

@@ -135,13 +135,13 @@ function useCreateInvestigationRuleMutation() {
     onSuccess: (_data, variables) => {
       addSuccessMessage(t('Successfully created investigation rule'));
       // invalidate the rule-exists query
-      queryClient.invalidateQueries(
-        makeRuleExistsQueryKey(
+      queryClient.invalidateQueries({
+        queryKey: makeRuleExistsQueryKey(
           variables.query,
           variables.projects,
           variables.organization
-        )
-      );
+        ),
+      });
       trackAnalytics('dynamic_sampling.custom_rule_add', {
         organization: variables.organization,
         projects: variables.projects,

+ 2 - 4
static/app/utils/metrics/useBlockMetric.tsx

@@ -32,7 +32,7 @@ export const useBlockMetric = (project: Project) => {
   const {slug} = useOrganization();
   const queryClient = useQueryClient();
 
-  const options = {
+  return useMutation({
     mutationFn: (data: BlockMutationData) => {
       return api.requestPromise(`/projects/${slug}/${project.slug}/metrics/visibility/`, {
         method: 'PUT',
@@ -84,7 +84,5 @@ export const useBlockMetric = (project: Project) => {
     onError: () => {
       addErrorMessage(t('An error occurred while updating the metric'));
     },
-  };
-
-  return useMutation(options);
+  });
 };

+ 3 - 3
static/app/views/issueList/mutations/useDeleteSavedSearch.tsx

@@ -44,9 +44,9 @@ export const useDeleteSavedSearchOptimistic = (
       });
     },
     onMutate: async variables => {
-      await queryClient.cancelQueries(
-        makeFetchSavedSearchesForOrgQueryKey({orgSlug: variables.orgSlug})
-      );
+      await queryClient.cancelQueries({
+        queryKey: makeFetchSavedSearchesForOrgQueryKey({orgSlug: variables.orgSlug}),
+      });
 
       const previousSavedSearches = getApiQueryData<SavedSearch[]>(
         queryClient,

+ 1 - 1
static/app/views/settings/account/accountEmails.tsx

@@ -33,7 +33,7 @@ function AccountEmails() {
   const queryClient = useQueryClient();
 
   const handleSubmitSuccess: FormProps['onSubmitSuccess'] = (_change, model, id) => {
-    queryClient.invalidateQueries(makeEmailsEndpointKey());
+    queryClient.invalidateQueries({queryKey: makeEmailsEndpointKey()});
 
     if (id === undefined) {
       return;

+ 35 - 31
static/app/views/settings/account/accountSecurity/accountSecurityDetails.tsx

@@ -69,8 +69,8 @@ function AccountSecurityDetails({deleteDisabled, onRegenerateBackupCodes}: Props
     staleTime: 0,
   });
 
-  const {mutate: remove, isLoading: isRemoveLoading} = useMutation(
-    ({id, device}: {id: string; device?: AuthenticatorDevice}) => {
+  const {mutate: remove, isLoading: isRemoveLoading} = useMutation({
+    mutationFn: ({id, device}: {id: string; device?: AuthenticatorDevice}) => {
       // if the device is defined, it means that U2f is being removed
       // reason for adding a trailing slash is a result of the endpoint on line 109 needing it but it can't be set there as if deviceId is None, the route will end with '//'
       const deviceId = device ? `${device.key_handle}/` : '';
@@ -78,23 +78,29 @@ function AccountSecurityDetails({deleteDisabled, onRegenerateBackupCodes}: Props
         method: 'DELETE',
       });
     },
-    {
-      onSuccess: (_, {device}) => {
-        const deviceName = device ? device.name : t('Authenticator');
-        addSuccessMessage(t('%s has been removed', deviceName));
-      },
-      onError: (_, {device}) => {
-        const deviceName = device ? device.name : t('Authenticator');
-        addErrorMessage(t('Error removing %s', deviceName));
-      },
-      onSettled: () => {
-        queryClient.invalidateQueries(getAuthenticatorQueryKey(authId));
-      },
-    }
-  );
+    onSuccess: (_, {device}) => {
+      const deviceName = device ? device.name : t('Authenticator');
+      addSuccessMessage(t('%s has been removed', deviceName));
+    },
+    onError: (_, {device}) => {
+      const deviceName = device ? device.name : t('Authenticator');
+      addErrorMessage(t('Error removing %s', deviceName));
+    },
+    onSettled: () => {
+      queryClient.invalidateQueries(getAuthenticatorQueryKey(authId));
+    },
+  });
 
-  const {mutate: rename, isLoading: isRenameLoading} = useMutation(
-    ({id, device, name}: {device: AuthenticatorDevice; id: string; name: string}) => {
+  const {mutate: rename, isLoading: isRenameLoading} = useMutation({
+    mutationFn: ({
+      id,
+      device,
+      name,
+    }: {
+      device: AuthenticatorDevice;
+      id: string;
+      name: string;
+    }) => {
       return api.requestPromise(`${ENDPOINT}${id}/${device.key_handle}/`, {
         method: 'PUT',
         data: {
@@ -102,19 +108,17 @@ function AccountSecurityDetails({deleteDisabled, onRegenerateBackupCodes}: Props
         },
       });
     },
-    {
-      onSuccess: () => {
-        navigate(`/settings/account/security/mfa/${authId}`);
-        addSuccessMessage(t('Device was renamed'));
-      },
-      onError: () => {
-        addErrorMessage(t('Error renaming the device'));
-      },
-      onSettled: () => {
-        queryClient.invalidateQueries(getAuthenticatorQueryKey(authId));
-      },
-    }
-  );
+    onSuccess: () => {
+      navigate(`/settings/account/security/mfa/${authId}`);
+      addSuccessMessage(t('Device was renamed'));
+    },
+    onError: () => {
+      addErrorMessage(t('Error renaming the device'));
+    },
+    onSettled: () => {
+      queryClient.invalidateQueries(getAuthenticatorQueryKey(authId));
+    },
+  });
 
   const handleRemove = (device?: AuthenticatorDevice) => {
     if (!authenticator?.authId) {

+ 18 - 22
static/app/views/settings/account/accountSecurity/accountSecurityWrapper.tsx

@@ -37,26 +37,24 @@ function AccountSecurityWrapper({children}: Props) {
     emailsRequest.refetch();
   }, [orgRequest, authenticatorsRequest, emailsRequest]);
 
-  const disableAuthenticatorMutation = useMutation(
-    async (auth: Authenticator) => {
+  const disableAuthenticatorMutation = useMutation({
+    mutationFn: async (auth: Authenticator) => {
       if (!auth || !auth.authId) {
         return;
       }
 
       await api.requestPromise(`${ENDPOINT}${auth.authId}/`, {method: 'DELETE'});
     },
-    {
-      onSuccess: () => {
-        handleRefresh();
-      },
-      onError: (_, auth) => {
-        addErrorMessage(t('Error disabling %s', auth.name));
-      },
-    }
-  );
+    onSuccess: () => {
+      handleRefresh();
+    },
+    onError: (_, auth) => {
+      addErrorMessage(t('Error disabling %s', auth.name));
+    },
+  });
 
-  const regenerateBackupCodesMutation = useMutation(
-    async () => {
+  const regenerateBackupCodesMutation = useMutation({
+    mutationFn: async () => {
       if (!authId) {
         return;
       }
@@ -65,15 +63,13 @@ function AccountSecurityWrapper({children}: Props) {
         method: 'PUT',
       });
     },
-    {
-      onSuccess: () => {
-        handleRefresh();
-      },
-      onError: () => {
-        addErrorMessage(t('Error regenerating backup codes'));
-      },
-    }
-  );
+    onSuccess: () => {
+      handleRefresh();
+    },
+    onError: () => {
+      addErrorMessage(t('Error regenerating backup codes'));
+    },
+  });
 
   if (
     orgRequest.isLoading ||

+ 24 - 26
static/app/views/settings/account/apiApplications/details.tsx

@@ -57,36 +57,34 @@ function ApiApplicationsDetails() {
     staleTime: 0,
   });
 
-  const {mutate: rotateClientSecret} = useMutation<RotateClientSecretResponse>(
-    () => {
+  const {mutate: rotateClientSecret} = useMutation<RotateClientSecretResponse>({
+    mutationFn: () => {
       return api.requestPromise(`/api-applications/${appId}/rotate-secret/`, {
         method: 'POST',
       });
     },
-    {
-      onSuccess: data => {
-        openModal(({Body, Header}) => (
-          <Fragment>
-            <Header>{t('Your new Client Secret')}</Header>
-            <Body>
-              <Alert type="info" showIcon>
-                {t('This will be the only time your client secret is visible!')}
-              </Alert>
-              <TextCopyInput aria-label={t('new-client-secret')}>
-                {data.clientSecret}
-              </TextCopyInput>
-            </Body>
-          </Fragment>
-        ));
-      },
-      onError: () => {
-        addErrorMessage(t('Error rotating secret'));
-      },
-      onSettled: () => {
-        queryClient.invalidateQueries(getAppQueryKey(appId));
-      },
-    }
-  );
+    onSuccess: data => {
+      openModal(({Body, Header}) => (
+        <Fragment>
+          <Header>{t('Your new Client Secret')}</Header>
+          <Body>
+            <Alert type="info" showIcon>
+              {t('This will be the only time your client secret is visible!')}
+            </Alert>
+            <TextCopyInput aria-label={t('new-client-secret')}>
+              {data.clientSecret}
+            </TextCopyInput>
+          </Body>
+        </Fragment>
+      ));
+    },
+    onError: () => {
+      addErrorMessage(t('Error rotating secret'));
+    },
+    onSettled: () => {
+      queryClient.invalidateQueries({queryKey: getAppQueryKey(appId)});
+    },
+  });
 
   if (isPending) {
     return <LoadingIndicator />;

+ 33 - 35
static/app/views/settings/account/apiTokens.tsx

@@ -40,52 +40,50 @@ export function ApiTokens() {
     refetch,
   } = useApiQuery<InternalAppApiToken[]>(API_TOKEN_QUERY_KEY, {staleTime: 0});
 
-  const {mutate: deleteToken} = useMutation(
-    (token: InternalAppApiToken) => {
+  const {mutate: deleteToken} = useMutation({
+    mutationFn: (token: InternalAppApiToken) => {
       return api.requestPromise('/api-tokens/', {
         method: 'DELETE',
         data: {tokenId: token.id},
       });
     },
-    {
-      onMutate: token => {
-        addLoadingMessage();
-        queryClient.cancelQueries(API_TOKEN_QUERY_KEY);
+    onMutate: token => {
+      addLoadingMessage();
+      queryClient.cancelQueries({queryKey: API_TOKEN_QUERY_KEY});
+
+      const previous = getApiQueryData<InternalAppApiToken[]>(
+        queryClient,
+        API_TOKEN_QUERY_KEY
+      );
+
+      setApiQueryData<InternalAppApiToken[]>(
+        queryClient,
+        API_TOKEN_QUERY_KEY,
+        oldTokenList => {
+          return oldTokenList?.filter(tk => tk.id !== token.id);
+        }
+      );
 
-        const previous = getApiQueryData<InternalAppApiToken[]>(
-          queryClient,
-          API_TOKEN_QUERY_KEY
-        );
+      return {previous};
+    },
+    onSuccess: _data => {
+      addSuccessMessage(t('Removed token'));
+    },
+    onError: (_error, _variables, context) => {
+      addErrorMessage(t('Unable to remove token. Please try again.'));
 
+      if (context?.previous) {
         setApiQueryData<InternalAppApiToken[]>(
           queryClient,
           API_TOKEN_QUERY_KEY,
-          oldTokenList => {
-            return oldTokenList?.filter(tk => tk.id !== token.id);
-          }
+          context.previous
         );
-
-        return {previous};
-      },
-      onSuccess: _data => {
-        addSuccessMessage(t('Removed token'));
-      },
-      onError: (_error, _variables, context) => {
-        addErrorMessage(t('Unable to remove token. Please try again.'));
-
-        if (context?.previous) {
-          setApiQueryData<InternalAppApiToken[]>(
-            queryClient,
-            API_TOKEN_QUERY_KEY,
-            context.previous
-          );
-        }
-      },
-      onSettled: () => {
-        queryClient.invalidateQueries(API_TOKEN_QUERY_KEY);
-      },
-    }
-  );
+      }
+    },
+    onSettled: () => {
+      queryClient.invalidateQueries({queryKey: API_TOKEN_QUERY_KEY});
+    },
+  });
 
   if (isPending) {
     return <LoadingIndicator />;

+ 1 - 1
static/app/views/settings/organizationTeams/index.tsx

@@ -61,7 +61,7 @@ export function OrganizationTeamsContainer(props: RouteComponentProps<{}, {}>) {
       setApiQueryData(queryClient, queryKey, newRequestList);
 
       // To be safer, trigger a refetch to ensure data is correct
-      queryClient.invalidateQueries(queryKey);
+      queryClient.invalidateQueries({queryKey});
 
       if (isApproved && requestToRemove) {
         const team = requestToRemove.team;

Some files were not shown because too many files changed in this diff