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, useLoading } from 'soapbox/hooks';
|
||||||
|
|
||||||
import { useApi } from 'soapbox/hooks';
|
|
||||||
|
|
||||||
import { EntityRequest } from './types';
|
import { EntityRequest } from './types';
|
||||||
import { toAxiosRequest } from './utils';
|
import { toAxiosRequest } from './utils';
|
||||||
|
|
||||||
function useEntityRequest() {
|
function useEntityRequest() {
|
||||||
const api = useApi();
|
const api = useApi();
|
||||||
const [isLoading, setIsLoading] = useState<boolean>(false);
|
const [isLoading, setPromise] = useLoading();
|
||||||
|
|
||||||
async function request(entityRequest: EntityRequest) {
|
function request(entityRequest: EntityRequest) {
|
||||||
setIsLoading(true);
|
const req = api.request(toAxiosRequest(entityRequest));
|
||||||
try {
|
return setPromise(req);
|
||||||
const response = await api.request(toAxiosRequest(entityRequest));
|
|
||||||
setIsLoading(false);
|
|
||||||
return response;
|
|
||||||
} catch (e) {
|
|
||||||
setIsLoading(false);
|
|
||||||
throw e;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return {
|
return {
|
||||||
|
|
|
@ -11,6 +11,7 @@ export { useGroupsPath } from './useGroupsPath';
|
||||||
export { useDimensions } from './useDimensions';
|
export { useDimensions } from './useDimensions';
|
||||||
export { useFeatures } from './useFeatures';
|
export { useFeatures } from './useFeatures';
|
||||||
export { useInstance } from './useInstance';
|
export { useInstance } from './useInstance';
|
||||||
|
export { useLoading } from './useLoading';
|
||||||
export { useLocale } from './useLocale';
|
export { useLocale } from './useLocale';
|
||||||
export { useOnScreen } from './useOnScreen';
|
export { useOnScreen } from './useOnScreen';
|
||||||
export { useOwnAccount } from './useOwnAccount';
|
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