traintrape-moi/client/hooks/mutations/useGeolocationMutation.ts

57 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-12-11 16:26:36 +00:00
import { AuthState } from "@/utils/features/auth/authSlice"
2024-12-11 00:30:21 +00:00
import { useMutation } from "@tanstack/react-query"
import { LocationObject } from "expo-location"
type ErrorResponse = {
error: string
message: string
statusCode: number
}
type onPostSuccessFunc = (data: any, variables: LocationObject, context: unknown) => void
type ErrorFuncProps = { response?: ErrorResponse, error?: Error }
type onErrorFunc = (props: ErrorFuncProps) => void
type PostProps = {
auth: AuthState
onPostSuccess?: onPostSuccessFunc
onError?: onErrorFunc
}
export const useGeolocationMutation = ({ auth, onPostSuccess, onError }: PostProps) => {
return useMutation({
mutationFn: async (location: LocationObject) => {
return fetch(`${process.env.EXPO_PUBLIC_TRAINTRAPE_MOI_SERVER}/geolocations/`, {
method: "POST",
headers: {
"Authorization": `Bearer ${auth.token}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
longitude: location.coords.longitude,
latitude: location.coords.latitude,
speed: location.coords.speed,
accuracy: location.coords.accuracy,
altitude: location.coords.altitude,
altitudeAccuracy: location.coords.altitudeAccuracy,
timestamp: location.timestamp,
})
}).then(resp => resp.json())
},
networkMode: 'offlineFirst',
onSuccess: async (data, location: LocationObject, context: unknown) => {
if (data.statusCode) {
if (onError)
onError({ response: data })
return
}
2024-12-11 00:30:21 +00:00
if (onPostSuccess)
onPostSuccess(data, location, context)
},
onError: async (error: Error) => {
if (onError)
onError({ error: error })
}
})
}