From 9d12173b874b8ffcbf595f465a594fdcf46fd830 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 23 Mar 2023 18:42:34 -0500 Subject: [PATCH] Add useLoading hook --- .../entity-store/hooks/useEntityRequest.ts | 19 +++++-------------- app/soapbox/hooks/index.ts | 1 + app/soapbox/hooks/useLoading.ts | 19 +++++++++++++++++++ 3 files changed, 25 insertions(+), 14 deletions(-) create mode 100644 app/soapbox/hooks/useLoading.ts diff --git a/app/soapbox/entity-store/hooks/useEntityRequest.ts b/app/soapbox/entity-store/hooks/useEntityRequest.ts index 7d2697e61f..678b8197c5 100644 --- a/app/soapbox/entity-store/hooks/useEntityRequest.ts +++ b/app/soapbox/entity-store/hooks/useEntityRequest.ts @@ -1,24 +1,15 @@ -import { useState } from 'react'; - -import { useApi } from 'soapbox/hooks'; +import { useApi, useLoading } from 'soapbox/hooks'; import { EntityRequest } from './types'; import { toAxiosRequest } from './utils'; function useEntityRequest() { const api = useApi(); - const [isLoading, setIsLoading] = useState(false); + const [isLoading, setPromise] = useLoading(); - async function request(entityRequest: EntityRequest) { - setIsLoading(true); - try { - const response = await api.request(toAxiosRequest(entityRequest)); - setIsLoading(false); - return response; - } catch (e) { - setIsLoading(false); - throw e; - } + function request(entityRequest: EntityRequest) { + const req = api.request(toAxiosRequest(entityRequest)); + return setPromise(req); } return { diff --git a/app/soapbox/hooks/index.ts b/app/soapbox/hooks/index.ts index 9cfd0a5e17..3f66a81472 100644 --- a/app/soapbox/hooks/index.ts +++ b/app/soapbox/hooks/index.ts @@ -11,6 +11,7 @@ export { useGroupsPath } from './useGroupsPath'; export { useDimensions } from './useDimensions'; export { useFeatures } from './useFeatures'; export { useInstance } from './useInstance'; +export { useLoading } from './useLoading'; export { useLocale } from './useLocale'; export { useOnScreen } from './useOnScreen'; export { useOwnAccount } from './useOwnAccount'; diff --git a/app/soapbox/hooks/useLoading.ts b/app/soapbox/hooks/useLoading.ts new file mode 100644 index 0000000000..51f15e5219 --- /dev/null +++ b/app/soapbox/hooks/useLoading.ts @@ -0,0 +1,19 @@ +import { useState } from 'react'; + +function useLoading() { + const [isLoading, setIsLoading] = useState(false); + + function setPromise(promise: Promise) { + setIsLoading(true); + + promise + .then(() => setIsLoading(false)) + .catch(() => setIsLoading(false)); + + return promise; + } + + return [isLoading, setPromise] as const; +} + +export { useLoading }; \ No newline at end of file