Add useLoading hook

This commit is contained in:
Alex Gleason 2023-03-23 18:42:34 -05:00
parent aa7e2f6965
commit 9d12173b87
No known key found for this signature in database
GPG key ID: 7211D1F99744FBB7
3 changed files with 25 additions and 14 deletions

View file

@ -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<boolean>(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 {

View file

@ -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';

View file

@ -0,0 +1,19 @@
import { useState } from 'react';
function useLoading() {
const [isLoading, setIsLoading] = useState<boolean>(false);
function setPromise<T>(promise: Promise<T>) {
setIsLoading(true);
promise
.then(() => setIsLoading(false))
.catch(() => setIsLoading(false));
return promise;
}
return [isLoading, setPromise] as const;
}
export { useLoading };