Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor: useDeferredFetch #608

Merged
merged 2 commits into from
Feb 3, 2025
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 7 additions & 15 deletions src/components/menus/content-contextual-menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -309,14 +309,12 @@ export default function ContentContextualMenu(props: Readonly<ContentContextualM
moveElementsToDirectory,
undefined,
moveElementErrorToString,
moveElementOnError,
false
moveElementOnError
);

const [renameCB, renameState] = useDeferredFetch(
// @ts-expect-error refacto typing of useDefferedFetch
renameElement,
(_elementUuid: string, renamedElement: any[]) => {
(renamedElement: any[]) => {
// if copied element is renamed
if (itemSelectionForCopy.sourceItemUuid === renamedElement[0]) {
dispatch(
Expand All @@ -342,41 +340,35 @@ export default function ContentContextualMenu(props: Readonly<ContentContextualM
return intl.formatMessage({ id: 'renameElementNotFoundError' });
}
return undefined;
},
undefined,
false
}
);

const [FiltersReplaceWithScriptCB] = useDeferredFetch(
replaceFiltersWithScript,
handleCloseDialog,
undefined,
handleLastError,
false
handleLastError
);

const [newScriptFromFiltersContingencyListCB] = useDeferredFetch(
newScriptFromFiltersContingencyList,
handleCloseDialog,
undefined,
handleLastError,
false
handleLastError
);

const [replaceFormContingencyListWithScriptCB] = useDeferredFetch(
replaceFormContingencyListWithScript,
handleCloseDialog,
undefined,
handleLastError,
false
handleLastError
);

const [newScriptFromFilterCB] = useDeferredFetch(
newScriptFromFilter,
handleCloseDialog,
undefined,
handleLastError,
false
handleLastError
);

const noCreationInProgress = useCallback(() => selectedElements.every((el) => el.hasMetadata), [selectedElements]);
Expand Down
51 changes: 19 additions & 32 deletions src/components/menus/directory-tree-contextual-menu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ import { buildPathToFromMap } from '../treeview-utils';

export interface DirectoryTreeContextualMenuProps extends Omit<CommonContextualMenuProps, 'onClose'> {
directory: ElementAttributes | null;
onClose: (nextSelectedDirectoryId?: string | null) => void;
onClose: () => void;
openDialog: string;
setOpenDialog: (dialogId: string) => void;
restrictMenuItems: boolean;
Expand All @@ -80,37 +80,24 @@ export default function DirectoryTreeContextualMenu(props: Readonly<DirectoryTre
setOpenDialog(dialogId);
};

const handleCloseDialog = useCallback(
(nextSelectedDirectoryId: string | null = null) => {
onClose(nextSelectedDirectoryId);
setOpenDialog(DialogsId.NONE);
setHideMenu(false);
setDeleteError('');
},
[onClose, setOpenDialog]
);
const handleCloseDialog = useCallback(() => {
onClose();
setOpenDialog(DialogsId.NONE);
setHideMenu(false);
setDeleteError('');
}, [onClose, setOpenDialog]);

const [renameCB, renameState] = useDeferredFetch(
// @ts-expect-error refacto typing of useDefferedFetch
renameElement,
handleCloseDialog,
(HTTPStatusCode: number) => {
if (HTTPStatusCode === 403) {
return intl.formatMessage({ id: 'renameDirectoryError' });
}
return undefined;
},
undefined,
false
);
const [renameCB, renameState] = useDeferredFetch(renameElement, handleCloseDialog, (HTTPStatusCode: number) => {
if (HTTPStatusCode === 403) {
return intl.formatMessage({ id: 'renameDirectoryError' });
}
return undefined;
});

const [insertDirectoryCB, insertDirectoryState] = useDeferredFetch(insertDirectory, (response: ElementAttributes) =>
handleCloseDialog(response?.elementUuid)
);
const [insertDirectoryCB, insertDirectoryState] = useDeferredFetch(insertDirectory, () => handleCloseDialog());

const [insertRootDirectoryCB, insertRootDirectoryState] = useDeferredFetch(
insertRootDirectory,
(response: ElementAttributes) => handleCloseDialog(response?.elementUuid)
const [insertRootDirectoryCB, insertRootDirectoryState] = useDeferredFetch(insertRootDirectory, () =>
handleCloseDialog()
);

const itemSelectionForCopy = useSelector((state: AppState) => state.itemSelectionForCopy);
Expand Down Expand Up @@ -196,14 +183,14 @@ export default function DirectoryTreeContextualMenu(props: Readonly<DirectoryTre
(elementsUuid: UUID) => {
setDeleteError('');
deleteElement(elementsUuid)
.then(() => handleCloseDialog(directory?.parentUuid))
.then(() => handleCloseDialog())
.catch((error: any) => {
// show the error message and don't close the dialog
setDeleteError(error.message);
handleError(error.message);
});
},
[handleCloseDialog, directory?.parentUuid, handleError]
[handleCloseDialog, handleError]
);

// Allowance
Expand Down Expand Up @@ -302,7 +289,7 @@ export default function DirectoryTreeContextualMenu(props: Readonly<DirectoryTre
});
});
}
handleCloseDialog(null);
handleCloseDialog();
},
[directory, handleCloseDialog, snackError, treeData.mapData]
);
Expand Down
3 changes: 1 addition & 2 deletions src/components/toolbars/content-toolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,7 @@ export default function ContentToolbar(props: Readonly<ContentToolbarProps>) {
moveElementsToDirectory,
undefined,
moveElementErrorToString,
moveElementOnError,
false
moveElementOnError
);

// Allowance
Expand Down
40 changes: 13 additions & 27 deletions src/utils/custom-hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,9 @@ interface MultipleAction<T> {
*/
export const useDeferredFetch = <T, TArgs extends unknown[] = any[]>(
fetchFunction: GenericFunction<T, TArgs>,
onSuccess?: (data: T, args: TArgs) => void,
onSuccess?: (args: TArgs, data?: T) => void,
errorToString?: (status: number) => string | undefined,
onError?: (errorMessage: string, args: TArgs) => void,
hasResult: boolean = true
onError?: (errorMessage: string, args: TArgs) => void
): [(...args: TArgs) => void, FetchState<T>] => {
const initialState: FetchState<T> = {
status: FetchStatus.IDLE,
Expand Down Expand Up @@ -124,25 +123,13 @@ export const useDeferredFetch = <T, TArgs extends unknown[] = any[]>(
dispatch({ type: ActionType.START });
try {
// Params resolution
const response = await fetchFunction(...args);

if (hasResult) {
const data = response;
dispatch({
type: ActionType.SUCCESS,
payload: data,
});
if (onSuccess) {
onSuccess(data, args);
}
} else {
dispatch({
type: ActionType.SUCCESS,
});
if (onSuccess) {
onSuccess(null as unknown as T, args);
}
}
const data = await fetchFunction(...args);
console.log(`deffered data: ${JSON.stringify(data)}`);
dispatch({
type: ActionType.SUCCESS,
payload: data,
});
onSuccess?.(args, data);
} catch (error: any) {
if (!error.status) {
// an http error
Expand All @@ -153,7 +140,7 @@ export const useDeferredFetch = <T, TArgs extends unknown[] = any[]>(
}
}
},
[fetchFunction, onSuccess, handleError, hasResult]
[fetchFunction, onSuccess, handleError]
);

const fetchCallback = useCallback((...args: TArgs) => fetchData(...args), [fetchData]);
Expand Down Expand Up @@ -186,8 +173,7 @@ export const useMultipleDeferredFetch = <T>(
fetchFunction: GenericFunction<T>,
onSuccess?: (data: T[]) => void,
errorToString?: (status: number) => string | undefined,
onError?: (errorMessages: string[], params: unknown[], paramsOnError: unknown[]) => void,
hasResult: boolean = true
onError?: (errorMessages: string[], params: unknown[], paramsOnError: unknown[]) => void
): [(cbParamsList: unknown[][]) => void] => {
const initialState: MultipleFetchState<T> = {
public: {
Expand Down Expand Up @@ -253,7 +239,7 @@ export const useMultipleDeferredFetch = <T>(

const [paramList, setParamList] = useState<unknown[][]>([]);

const onInstanceSuccess = useCallback((data: T, paramsOnSuccess: unknown[]) => {
const onInstanceSuccess = useCallback((paramsOnSuccess: unknown[], data?: T) => {
dispatch({
type: ActionType.ADD_SUCCESS,
payload: data,
Expand All @@ -271,7 +257,7 @@ export const useMultipleDeferredFetch = <T>(
});
}, []);

const [fetchCB] = useDeferredFetch(fetchFunction, onInstanceSuccess, errorToString, onInstanceError, hasResult);
const [fetchCB] = useDeferredFetch(fetchFunction, onInstanceSuccess, errorToString, onInstanceError);

const fetchCallback = useCallback(
(cbParamsList: unknown[][]) => {
Expand Down
Loading