traintrape-moi/client/components/GeolocationProvider.tsx

54 lines
2.0 KiB
TypeScript

import { ReactNode, useEffect } from 'react'
import { useAuth } from '@/hooks/useAuth'
import { useQueuedLocations, useSetLastPlayerLocations, useUnqueueLocation } from '@/hooks/useLocation'
import { useGeolocationMutation } from '@/hooks/mutations/useGeolocationMutation'
import { useStartGeolocationServiceEffect } from '@/utils/geolocation'
import { Platform } from 'react-native'
import { useQuery } from '@tanstack/react-query'
import { isAuthValid } from '@/utils/features/auth/authSlice'
export default function GeolocationProvider({ children }: { children: ReactNode }) {
useStartGeolocationServiceEffect()
const auth = useAuth()
const geolocationsQueue = useQueuedLocations()
const unqueueLocation = useUnqueueLocation()
const setLastPlayerLocations = useSetLastPlayerLocations()
const geolocationMutation = useGeolocationMutation({
auth,
onPostSuccess: (data) => {
unqueueLocation(data)
geolocationMutation.reset()
},
onError: ({ response, error }) => { console.error(response, error) }
})
useEffect(() => {
if (geolocationsQueue.length === 0 || geolocationMutation.isPending || Platform.OS === "web")
return
const locToSend = geolocationsQueue[0]
geolocationMutation.mutate(locToSend)
}, [auth, geolocationsQueue])
const lastLocationsQuery = useQuery({
queryKey: ['get-last-locations', auth.token],
queryFn: () => fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/geolocations/last-locations/`, {
method: "GET",
headers: {
"Authorization": `Bearer ${auth.token}`,
"Content-Type": "application/json",
},
}).then(resp => resp.json()),
initialData: [],
enabled: isAuthValid(auth),
refetchInterval: 5000,
})
useEffect(() => {
if (lastLocationsQuery.isSuccess && lastLocationsQuery.data)
setLastPlayerLocations(lastLocationsQuery.data)
}, [lastLocationsQuery.status, lastLocationsQuery.dataUpdatedAt])
return <>
{children}
</>
}