useModifySavedSearch.tsx 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. import {SavedSearch, SavedSearchType, SavedSearchVisibility} from 'sentry/types';
  2. import {
  3. setApiQueryData,
  4. useMutation,
  5. UseMutationOptions,
  6. useQueryClient,
  7. } from 'sentry/utils/queryClient';
  8. import RequestError from 'sentry/utils/requestError/requestError';
  9. import useApi from 'sentry/utils/useApi';
  10. import {makeFetchSavedSearchesForOrgQueryKey} from 'sentry/views/issueList/queries/useFetchSavedSearchesForOrg';
  11. type ModifySavedSearchVariables = {
  12. id: string;
  13. name: string;
  14. orgSlug: string;
  15. query: string;
  16. sort: string | null;
  17. type: SavedSearchType;
  18. visibility: SavedSearchVisibility;
  19. };
  20. type ModifySavedSearchResponse = SavedSearch;
  21. export const useModifySavedSearch = (
  22. options: Omit<
  23. UseMutationOptions<
  24. ModifySavedSearchResponse,
  25. RequestError,
  26. ModifySavedSearchVariables
  27. >,
  28. 'mutationFn'
  29. > = {}
  30. ) => {
  31. const api = useApi();
  32. const queryClient = useQueryClient();
  33. return useMutation<ModifySavedSearchResponse, RequestError, ModifySavedSearchVariables>(
  34. {
  35. ...options,
  36. mutationFn: ({id, orgSlug, ...data}: ModifySavedSearchVariables) =>
  37. api.requestPromise(`/organizations/${orgSlug}/searches/${id}/`, {
  38. method: 'PUT',
  39. data,
  40. }),
  41. onSuccess: (savedSearch, parameters, context) => {
  42. setApiQueryData<SavedSearch[]>(
  43. queryClient,
  44. makeFetchSavedSearchesForOrgQueryKey({orgSlug: parameters.orgSlug}),
  45. oldData => {
  46. if (!Array.isArray(oldData)) {
  47. return oldData;
  48. }
  49. return oldData.map(search =>
  50. search?.id === parameters.id ? savedSearch : search
  51. );
  52. }
  53. );
  54. options.onSuccess?.(savedSearch, parameters, context);
  55. },
  56. }
  57. );
  58. };