Add useLoading hook
This commit is contained in:
parent
aa7e2f6965
commit
9d12173b87
3 changed files with 25 additions and 14 deletions
|
@ -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 {
|
||||
|
|
|
@ -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';
|
||||
|
|
19
app/soapbox/hooks/useLoading.ts
Normal file
19
app/soapbox/hooks/useLoading.ts
Normal 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 };
|
Loading…
Reference in a new issue