Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 | 6x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 26x 4x 4x 4x 26x 36x 36x 36x 26x 26x 26x 26x 5x 26x 26x 16x 26x 26x 26x 26x 26x 26x | import React, { useEffect, useRef, useState } from "react";
import { useQuery, useInfiniteQuery, useQueryClient } from "react-query";
import { useInView } from "react-intersection-observer";
import { isEmpty } from "lodash";
import { customInstance } from "@services/api";
import { ROWS_PER_PAGE, usePagination } from "@hooks/common/usePagination";
import { detectMobile } from "@utils/index";
import { useCachedList } from "@hooks/common/useCachedList";
import { buildAccountsUrl } from "@services/api/utils.api";
import { useAppDispatch, useAppSelector } from "@redux/hooks";
import { updatePermissions } from "@redux/slices/app";
import { useAccessControl } from "features/Permissions/AccessControl";
import RESOURCE_BASE, { OPERATIONS } from "@constants/permissions";
import { selectSelectedAccount } from "@redux/slices/auth/accounts";
import { useGetCurrentMerchantId } from "@hooks/common";
import { QKEY_USER_PERMISSIONS } from "@constants/queryKeys";
import useMasqueradeReducer from "@hooks/Reducers/useMasqueradeReducer";
import { LibraryImage } from "@components/Settings/MediaLibrary/library.types";
export const useGetAllImages = (
elementsPerPage = ROWS_PER_PAGE,
invalidateOnPageChange = false,
isInfinite = false,
) => {
const client = useQueryClient();
const dispatch = useAppDispatch();
const { page, setPage } = usePagination(0, "");
const { img } = useGetCurrentMerchantId();
const selectedUser = useAppSelector(selectSelectedAccount);
const startIndex = (page - 1) * elementsPerPage;
const isListAllowed = useAccessControl({
resource: RESOURCE_BASE.MEDIA_ITEM,
operation: OPERATIONS.LIST,
withPortal: true,
});
const { id: masqueradeId } = useMasqueradeReducer();
const merchantId = selectedUser?.id || 0;
const accountId = selectedUser?.userAccID || 0;
const { allData, invalidateCache } = useCachedList(
"get-all-media-items",
false,
page,
);
const loadingRef = useRef<boolean>(false);
const { ref: scrollRef, inView } = useInView({ threshold: 0 });
const permissionsState = client.getQueryState([
QKEY_USER_PERMISSIONS,
accountId,
merchantId,
masqueradeId,
]);
const fetchImages = async ({ pageParam = 1 }) => {
const queryUrl = `media-items?max=${elementsPerPage}&after=${
(pageParam - 1) * elementsPerPage
}&sort=-id&page=${pageParam}`;
const response = await customInstance({
url: buildAccountsUrl(queryUrl),
method: "GET",
});
return { ...response, page: pageParam };
};
const infiniteQuery = useInfiniteQuery(
["get-all-media-items-infinite"],
fetchImages,
{
enabled: isInfinite && isListAllowed,
getNextPageParam: (lastPage) => {
const total = lastPage?.total || 0;
const currentCount = lastPage.page * elementsPerPage;
return currentCount < total ? lastPage.page + 1 : undefined;
},
onError(err: any) {
if (err?.not_authorized) {
dispatch(updatePermissions({ all_media_items: true }));
}
},
},
);
const paginationQuery = useQuery(
["get-all-media-items", page, elementsPerPage],
() => fetchImages({ pageParam: page }),
{
enabled: !isInfinite && isListAllowed,
refetchOnWindowFocus: false,
retry: 2,
onError(err: any) {
if (err?.not_authorized) {
dispatch(updatePermissions({ all_media_items: true }));
}
},
},
);
// Trigger infinite scroll
useEffect(() => {
Iif (
isInfinite &&
inView &&
infiniteQuery.hasNextPage &&
!infiniteQuery.isFetchingNextPage &&
!loadingRef.current
) {
loadingRef.current = true;
infiniteQuery.fetchNextPage().finally(() => {
setTimeout(() => (loadingRef.current = false), 700);
});
}
}, [inView, isInfinite, infiniteQuery]);
useEffect(() => {
Iif (invalidateOnPageChange) {
invalidateCache();
}
}, [page]);
const merchantImage = (img || selectedUser?.img)?.replace("/thumb", "");
// i removed this since we cant delete this image i asked BE to fix then can be updated
// const merchantMedia = merchantImage ? [{ URL: merchantImage, id: 0 }] : [];
const usedData = isInfinite
? infiniteQuery.data?.pages.flatMap((page) => page?.data || []) || []
: detectMobile()
? allData
: paginationQuery.data?.data || [];
const totalRows =
infiniteQuery.data?.pages?.[0]?.total || paginationQuery.data?.total || 0;
const currentLength = usedData.length;
const handlePageChange = (
event: React.ChangeEvent<unknown> | any,
value: number,
) => setPage(value);
const setNextPage = () => setPage((prev) => prev + 1);
const setPrevPage = () => setPage((prev) => prev - 1);
return {
error: infiniteQuery.error || paginationQuery.error,
images: usedData as LibraryImage[],
isLoading: isInfinite
? (infiniteQuery.isLoading || permissionsState?.isFetching) &&
isEmpty(usedData)
: paginationQuery.isLoading || permissionsState?.isFetching,
page,
totalRows: merchantImage ? totalRows + 1 : totalRows,
handlePageChange,
setPage: setNextPage,
setNextPage,
setPrevPage,
setPageOnSwipe: setPage,
currentPageRows: usedData,
loadingRef,
scrollRef,
hasNextPage: isInfinite
? infiniteQuery.hasNextPage
: currentLength < totalRows,
allDataDesktop: () => {
const caches = client.getQueryCache().findAll("get-all-media-items");
return caches.reduce((acc: any, v) => {
if (v?.state?.data) {
const items = (v.state.data as any)?.data ?? [];
const unique = items.filter(
(item: any) => !acc.some((a: any) => a.id === item.id),
);
return [...acc, ...unique];
}
return acc;
}, []);
},
};
};
|