Files
2024-02-15 17:01:50 +00:00

60 lines
2.0 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
import {t} from 'sentry/locale';
import type {SavedSearch, SavedSearchType} from 'sentry/types';
import type {UseMutationOptions} from 'sentry/utils/queryClient';
import {setApiQueryData, useMutation, useQueryClient} from 'sentry/utils/queryClient';
import type RequestError from 'sentry/utils/requestError/requestError';
import useApi from 'sentry/utils/useApi';
import {makeFetchSavedSearchesForOrgQueryKey} from 'sentry/views/issueList/queries/useFetchSavedSearchesForOrg';
type PinSavedSearchVariables = {
orgSlug: string;
query: string;
sort: string | null;
type: SavedSearchType;
};
type PinSavedSearchResponse = SavedSearch;
export const usePinSearch = (
options: Omit<
UseMutationOptions<PinSavedSearchResponse, RequestError, PinSavedSearchVariables>,
'mutationFn'
> = {}
) => {
const api = useApi();
const queryClient = useQueryClient();
return useMutation<PinSavedSearchResponse, RequestError, PinSavedSearchVariables>({
...options,
mutationFn: ({orgSlug, query, type, sort}) =>
api.requestPromise(`/organizations/${orgSlug}/pinned-searches/`, {
method: 'PUT',
data: {query, type, sort},
}),
onSuccess: (savedSearch, variables, context) => {
setApiQueryData<SavedSearch[]>(
queryClient,
makeFetchSavedSearchesForOrgQueryKey({orgSlug: variables.orgSlug}),
oldData => {
if (!Array.isArray(oldData)) {
return oldData;
}
return [
savedSearch,
// Make sure we remove any existing pinned searches
...oldData.filter(search => !search.isPinned),
];
}
);
addSuccessMessage(t('When you come back you’ll see this search by default.'));
options.onSuccess?.(savedSearch, variables, context);
},
onError: (error, variables, context) => {
addErrorMessage(t('Unable to set the default search.'));
options.onError?.(error, variables, context);
},
});
};