upd: caching data
Deskripsi: - update caching pada fitur utama -yg fitur divisi belom
This commit is contained in:
@@ -12,6 +12,7 @@ import { apiGetProfile } from "@/lib/api";
|
||||
import { setEntities } from "@/lib/entitiesSlice";
|
||||
import { useAuthSession } from "@/providers/AuthProvider";
|
||||
import { useTheme } from "@/providers/ThemeProvider";
|
||||
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||
import { LinearGradient } from "expo-linear-gradient";
|
||||
import { Stack } from "expo-router";
|
||||
import { useEffect, useState } from "react";
|
||||
@@ -23,28 +24,46 @@ import { useDispatch, useSelector } from "react-redux";
|
||||
export default function Home() {
|
||||
const entities = useSelector((state: any) => state.entities)
|
||||
const dispatch = useDispatch()
|
||||
const queryClient = useQueryClient()
|
||||
const { token, decryptToken, signOut } = useAuthSession()
|
||||
const { colors } = useTheme();
|
||||
const insets = useSafeAreaInsets()
|
||||
const [refreshing, setRefreshing] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
handleUserLogin()
|
||||
}, [dispatch]);
|
||||
const { data: profile, isError } = useQuery({
|
||||
queryKey: ['profile'],
|
||||
queryFn: async () => {
|
||||
const hasil = await decryptToken(String(token?.current))
|
||||
const data = await apiGetProfile({ id: hasil })
|
||||
return data.data
|
||||
},
|
||||
enabled: !!token?.current,
|
||||
staleTime: 0, // Ensure it refetches every time the component mounts
|
||||
})
|
||||
|
||||
async function handleUserLogin() {
|
||||
const hasil = await decryptToken(String(token?.current))
|
||||
apiGetProfile({ id: hasil })
|
||||
.then((data) => dispatch(setEntities(data.data)))
|
||||
.catch((error) => {
|
||||
signOut()
|
||||
});
|
||||
}
|
||||
// Sync to Redux for global usage
|
||||
useEffect(() => {
|
||||
if (profile) {
|
||||
dispatch(setEntities(profile))
|
||||
}
|
||||
}, [profile, dispatch])
|
||||
|
||||
// Auto Sign Out if profile fetch fails (e.g. invalid/expired token)
|
||||
useEffect(() => {
|
||||
if (isError) {
|
||||
signOut()
|
||||
}
|
||||
}, [isError, signOut])
|
||||
|
||||
const handleRefresh = async () => {
|
||||
setRefreshing(true)
|
||||
handleUserLogin()
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
// Invalidate all queries related to the home screen
|
||||
await queryClient.invalidateQueries({ queryKey: ['profile'] })
|
||||
await queryClient.invalidateQueries({ queryKey: ['banners'] })
|
||||
await queryClient.invalidateQueries({ queryKey: ['homeData'] })
|
||||
|
||||
// Artificial delay to show refresh indicator if sync is too fast
|
||||
await new Promise(resolve => setTimeout(resolve, 1000));
|
||||
setRefreshing(false)
|
||||
};
|
||||
|
||||
|
||||
Reference in New Issue
Block a user