Files
mobile-darmasaba/app/(application)/division/index.tsx
amaliadwiy ccf8ee1caf upd: caching data
Deskripsi:
- update caching pada fitur utama -yg fitur divisi belom
2026-04-20 14:23:14 +08:00

302 lines
12 KiB
TypeScript

import BorderBottomItem from "@/components/borderBottomItem";
import ButtonTab from "@/components/buttonTab";
import InputSearch from "@/components/inputSearch";
import LabelStatus from "@/components/labelStatus";
import PaperGridContent from "@/components/paperGridContent";
import Skeleton from "@/components/skeleton";
import SkeletonTwoItem from "@/components/skeletonTwoItem";
import Text from "@/components/Text";
import WrapTab from "@/components/wrapTab";
import Styles from "@/constants/Styles";
import { apiGetDivision } from "@/lib/api";
import { useAuthSession } from "@/providers/AuthProvider";
import { useTheme } from "@/providers/ThemeProvider";
import {
AntDesign,
Feather,
Ionicons,
MaterialCommunityIcons
} from "@expo/vector-icons";
import { useInfiniteQuery, useQueryClient } from "@tanstack/react-query";
import { router, useLocalSearchParams } from "expo-router";
import { useEffect, useMemo, useState } from "react";
import { Pressable, RefreshControl, View, VirtualizedList } from "react-native";
import { useSelector } from "react-redux";
type Props = {
id: string;
name: string;
desc: string;
jumlah_member: number;
};
export default function ListDivision() {
const { active, group, cat } = useLocalSearchParams<{
active?: string;
group?: string;
cat?: string;
}>();
const [isList, setList] = useState(false);
const entityUser = useSelector((state: any) => state.user)
const { token, decryptToken } = useAuthSession()
const { colors } = useTheme();
const [search, setSearch] = useState("")
const queryClient = useQueryClient()
const [status, setStatus] = useState<'true' | 'false'>(active == 'false' ? 'false' : 'true')
const [category, setCategory] = useState<'divisi-saya' | 'semua'>(cat == 'semua' ? 'semua' : 'divisi-saya')
const update = useSelector((state: any) => state.divisionUpdate)
const [refreshing, setRefreshing] = useState(false)
// TanStack Query for Divisions with Infinite Scroll
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
isLoading,
refetch
} = useInfiniteQuery({
queryKey: ['divisions', { status, search, group, category }],
queryFn: async ({ pageParam = 1 }) => {
const hasil = await decryptToken(String(token?.current));
const response = await apiGetDivision({
user: hasil,
active: status,
search: search,
group: String(group),
kategori: category,
page: pageParam
});
return response;
},
initialPageParam: 1,
getNextPageParam: (lastPage, allPages) => {
return lastPage.data.length > 0 ? allPages.length + 1 : undefined;
},
enabled: !!token?.current,
staleTime: 0,
})
// Refetch when manual update state changes
useEffect(() => {
refetch()
}, [update, refetch])
// Flatten pages into a single data array
const flatData = useMemo(() => {
return data?.pages.flatMap(page => page.data) || [];
}, [data])
// Get nameGroup from the first available page
const nameGroup = useMemo(() => {
return data?.pages[0]?.filter?.name || "";
}, [data])
const handleRefresh = async () => {
setRefreshing(true)
await queryClient.invalidateQueries({ queryKey: ['divisions'] })
setRefreshing(false)
};
const loadMoreData = () => {
if (hasNextPage && !isFetchingNextPage) {
fetchNextPage()
}
};
const arrSkeleton = [0, 1, 2]
const getItem = (_data: unknown, index: number): Props => ({
id: flatData[index]?.id,
name: flatData[index]?.name,
desc: flatData[index]?.desc,
jumlah_member: flatData[index]?.jumlah_member,
})
return (
<View style={[Styles.p15, { flex: 1, backgroundColor: colors.background }]}>
<View>
{
entityUser.role != "user" && entityUser.role != "coadmin" ?
<WrapTab>
<ButtonTab
active={status == "false" ? "false" : "true"}
value="true"
onPress={() => { setStatus("true") }}
label="Aktif"
icon={
<Feather
name="check-circle"
color={status == "false" ? colors.dimmed : "white"}
size={20}
/>
}
n={2}
/>
<ButtonTab
active={status == "false" ? "false" : "true"}
value="false"
onPress={() => { setStatus("false") }}
label="Tidak Aktif"
icon={
<AntDesign
name="closecircleo"
color={status == "true" ? colors.dimmed : "white"}
size={20}
/>
}
n={2}
/>
</WrapTab>
:
<WrapTab>
<ButtonTab
active={category == "semua" ? "false" : "true"}
value="true"
onPress={() => { setCategory("divisi-saya") }}
label="Divisi Saya"
icon={
<Ionicons
name="file-tray-outline"
color={category == "semua" ? colors.dimmed : "white"}
size={20}
/>
}
n={2}
/>
<ButtonTab
active={category == "semua" ? "false" : "true"}
value="false"
onPress={() => { setCategory("semua") }}
label="Semua Divisi"
icon={
<Ionicons
name="file-tray-stacked-outline"
color={category == "semua" ? "white" : colors.dimmed}
size={20}
/>
}
n={2}
/>
</WrapTab>
}
<View style={[Styles.rowSpaceBetween, { alignItems: 'center' }]}>
<InputSearch width={68} onChange={setSearch} />
<Pressable
onPress={() => {
setList(!isList);
}}
>
<MaterialCommunityIcons
name={isList ? "format-list-bulleted" : "view-grid"}
color={colors.text}
size={30}
/>
</Pressable>
</View>
{(entityUser.role == "supadmin" || entityUser.role == "developer") && (
<View style={[Styles.mv05, Styles.rowOnly]}>
<Text>Filter :</Text>
<LabelStatus size="small" category="secondary" text={nameGroup} style={[Styles.mh05]} />
</View>
)}
</View>
<View style={[{ flex: 2 }, Styles.mt10]}>
{
isLoading ?
isList ?
arrSkeleton.map((item, index) => (
<SkeletonTwoItem key={index} />
))
:
arrSkeleton.map((item, index) => (
<Skeleton key={index} width={100} height={180} widthType="percent" borderRadius={10} />
))
:
flatData.length == 0 ? (
<View style={[Styles.mt15]}>
<Text style={[Styles.textDefault, { textAlign: 'center', color: colors.dimmed }]}>Tidak ada data</Text>
</View>
) : (
isList ? (
<View style={[Styles.h100]}>
<VirtualizedList
data={flatData}
style={[{ paddingBottom: 100 }]}
getItemCount={() => flatData.length}
getItem={getItem}
renderItem={({ item, index }: { item: Props, index: number }) => {
return (
<BorderBottomItem
key={index}
onPress={() => { router.push(`/division/${item.id}`) }}
borderType="bottom"
bgColor="transparent"
icon={
<View style={[Styles.iconContent]}>
<Feather name="users" size={25} color={'black'} />
</View>
}
title={item.name}
/>
)
}}
keyExtractor={(item, index) => String(index)}
onEndReached={loadMoreData}
onEndReachedThreshold={0.5}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={handleRefresh}
tintColor={colors.icon}
/>
}
/>
</View>
) : (
<View style={[Styles.h100]}>
<VirtualizedList
data={flatData}
style={[{ paddingBottom: 100 }]}
getItemCount={() => flatData.length}
getItem={getItem}
renderItem={({ item, index }: { item: Props, index: number }) => {
return (
<PaperGridContent
key={index}
onPress={() => {
router.push(`/division/${item.id}`);
}}
content="page"
title={item.name}
headerColor="primary"
contentPosition="top"
>
<Text style={[Styles.textDefault]} numberOfLines={2} ellipsizeMode="tail">{item.desc}</Text>
</PaperGridContent>
)
}}
keyExtractor={(item, index) => String(index)}
onEndReached={loadMoreData}
onEndReachedThreshold={0.5}
showsVerticalScrollIndicator={false}
refreshControl={
<RefreshControl
refreshing={refreshing}
onRefresh={handleRefresh}
tintColor={colors.icon}
/>
}
/>
</View>
)
)
}
</View>
</View>
);
}