useProjectSdkUpdates.tsx 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. import {useEffect, useMemo, useState} from 'react';
  2. import {Client} from 'sentry/api';
  3. import {RequestState} from 'sentry/types';
  4. import {Organization} from '../types/organization';
  5. import {Project, ProjectSdkUpdates} from '../types/project';
  6. import useApi from './useApi';
  7. function loadSdkUpdates(api: Client, orgSlug: string): Promise<ProjectSdkUpdates[]> {
  8. return api.requestPromise(`/organizations/${orgSlug}/sdk-updates/`);
  9. }
  10. interface UseProjectSdkOptions {
  11. organization: Organization;
  12. projectId: Project['id'] | null;
  13. }
  14. export function useProjectSdkUpdates(
  15. options: UseProjectSdkOptions
  16. ): RequestState<ProjectSdkUpdates | null> {
  17. const api = useApi();
  18. const [state, setState] = useState<RequestState<ProjectSdkUpdates[] | null>>({
  19. type: 'initial',
  20. });
  21. useEffect(() => {
  22. let unmounted = false;
  23. loadSdkUpdates(api, options.organization.slug)
  24. .then(data => {
  25. if (unmounted) {
  26. return;
  27. }
  28. setState({
  29. type: 'resolved',
  30. data,
  31. });
  32. })
  33. .catch(e => {
  34. if (unmounted) {
  35. return;
  36. }
  37. setState({
  38. type: 'errored',
  39. error: e,
  40. });
  41. });
  42. return () => {
  43. unmounted = true;
  44. };
  45. }, [api, options.organization.slug]);
  46. const stateForProject = useMemo((): RequestState<ProjectSdkUpdates | null> => {
  47. if (!options.projectId) {
  48. return {
  49. ...state,
  50. type: 'resolved',
  51. data: null,
  52. };
  53. }
  54. if (state.type === 'resolved') {
  55. return {
  56. ...state,
  57. type: 'resolved',
  58. data:
  59. state.type === 'resolved' && state.data
  60. ? state.data.find(sdk => sdk.projectId === options.projectId) ?? null
  61. : null,
  62. };
  63. }
  64. return state;
  65. }, [state, options.projectId]);
  66. return stateForProject;
  67. }