Skip to content

Instantly share code, notes, and snippets.

@rahsheen
Last active July 21, 2020 13:52
Show Gist options
  • Save rahsheen/9df8b1b10d0ad70a6dbbf5c9b54510e9 to your computer and use it in GitHub Desktop.
Save rahsheen/9df8b1b10d0ad70a6dbbf5c9b54510e9 to your computer and use it in GitHub Desktop.
Expo Location Context Provider
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