Skip to content

Commit 5578b54

Browse files
Add getCurrentLocation and LocationProvider
1 parent b7a0915 commit 5578b54

3 files changed

Lines changed: 77 additions & 1 deletion

File tree

src/index.ts

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,18 @@
11
import { useInterval } from './useInterval/useInterval'
22
import { AsyncState, getAsyncState } from './async-data/asyncState'
33
import { AsyncView } from './async-data/AsyncView'
4+
import {
5+
LocationProvider,
6+
LocationContext,
7+
LocationContextValue,
8+
} from './location-provider/LocationProvider'
49

5-
export { useInterval, AsyncState, getAsyncState, AsyncView }
10+
export {
11+
useInterval,
12+
AsyncState,
13+
getAsyncState,
14+
AsyncView,
15+
LocationProvider,
16+
LocationContext,
17+
LocationContextValue,
18+
}
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import React, { useEffect, useState } from 'react'
2+
import { createContext } from 'react'
3+
import { useInterval } from '../index'
4+
import { getCurrentLocation } from './getCurrentLocation'
5+
6+
export type LocationContextValue = {
7+
location: Position | null
8+
}
9+
10+
export const LocationContext = createContext<LocationContextValue>({
11+
location: null,
12+
})
13+
14+
export const LocationProvider: React.FC<{
15+
highAccuracy: boolean
16+
delay: number
17+
}> = ({ highAccuracy, delay, children }) => {
18+
const [location, setLocation] = useState<LocationContextValue>({
19+
location: null,
20+
})
21+
22+
const updateLocation = async () => {
23+
const position = await getCurrentLocation(highAccuracy).catch(
24+
() => location.location
25+
)
26+
setLocation({ location: position })
27+
}
28+
29+
useEffect(() => {
30+
updateLocation()
31+
}, [])
32+
33+
useInterval(() => {
34+
updateLocation()
35+
}, delay)
36+
37+
return (
38+
<LocationContext.Provider value={location}>
39+
{children}
40+
</LocationContext.Provider>
41+
)
42+
}
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
const getCurrentLocation = (highAccuracy = false): Promise<Position> => {
2+
return new Promise<Position>((resolve, reject) => {
3+
const successCallback = (position: Position): void => {
4+
resolve(position)
5+
}
6+
7+
const errorCallback = (error: PositionError) => {
8+
reject(error.message)
9+
}
10+
11+
if (navigator.geolocation) {
12+
navigator.geolocation.getCurrentPosition(successCallback, errorCallback, {
13+
enableHighAccuracy: highAccuracy,
14+
})
15+
} else {
16+
reject('Geolocation not supported')
17+
}
18+
})
19+
}
20+
21+
export { getCurrentLocation }

0 commit comments

Comments
 (0)