Created
August 13, 2019 12:20
-
-
Save itsMapleLeaf/54e3bc5e9e5efd8efafc65562050e4ba to your computer and use it in GitHub Desktop.
geolocation hook example
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
| function SomeComponent() { | |
| const { location, error } = useGeolocation() | |
| useEffect(() => { | |
| if (error) { | |
| Analytics.trackEvent("LocationService: ", error.message, error.code) | |
| handleLocationError(error) | |
| } | |
| }, [error]) | |
| // render something w/ location | |
| } |
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
| function useGeolocation() { | |
| const [location, setLocation] = useState() | |
| const [error, setError] = useState() | |
| useEffect(() => { | |
| Geolocation.watchPosition((location) => { | |
| setLocation(location) | |
| setError(undefined) // clear error if getting location was a success | |
| }, setError) | |
| return () => { | |
| // cleanup the watcher here | |
| } | |
| }, []) | |
| return { location, error } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment