Last active
July 21, 2020 13:52
-
-
Save rahsheen/9df8b1b10d0ad70a6dbbf5c9b54510e9 to your computer and use it in GitHub Desktop.
Expo Location Context Provider
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { createContext, useEffect, useState } from "react"; | |
import { ActivityIndicator, Text } from "react-native-paper"; | |
import { View } from "react-native"; | |
import * as Location from "expo-location"; | |
interface LocationContextType { | |
location?: Location.LocationData; | |
refresh: () => void; | |
error: string; | |
loading: boolean; | |
} | |
const LocationContext = createContext<LocationContextType>({ | |
location: undefined, | |
refresh: null, | |
error: "", | |
loading: false, | |
}); | |
const LocationProvider = (props: any) => { | |
const [location, setLocation] = useState<Location.LocationData>(); | |
const [error, setError] = useState(""); | |
const [perms, setPerms] = useState<Location.PermissionResponse>(); | |
const [loading, setLoading] = useState(false); | |
const checkPerms = async () => { | |
if (perms && perms.status === "granted") return; | |
const permsResponse = await Location.requestPermissionsAsync(); | |
setPerms(permsResponse); | |
if (permsResponse.status !== "granted") { | |
setError("Permission to access location was denied"); | |
} | |
}; | |
const refresh = async () => { | |
try { | |
setLoading(true); | |
checkPerms(); | |
const location = await Location.getCurrentPositionAsync({}); | |
setLocation(location); | |
} catch (error) { | |
console.error(error); | |
setError(error); | |
} finally { | |
setLoading(false); | |
} | |
}; | |
useEffect(() => { | |
refresh(); | |
}, []); | |
const locationContextValue = { location, refresh, error, loading }; | |
return <LocationContext.Provider value={locationContextValue} {...props} />; | |
}; | |
const useLocation = () => React.useContext(LocationContext); | |
export { LocationProvider, useLocation }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment