diff options
author | Nick Van Doorn <vandoorn.nick@gmail.com> | 2019-04-05 15:04:10 -0700 |
---|---|---|
committer | Nick Van Doorn <vandoorn.nick@gmail.com> | 2019-04-05 15:04:10 -0700 |
commit | 3cb9cfa5c3b9401ed7cd4a7b8f5b4831f7027403 (patch) | |
tree | fed29595a14e6e253e93af5a4602a7f1a97fa4d3 | |
parent | 8db536cf3b420c65eb87b77415d3e70ac6a68cfa (diff) |
Define calculation helper in closure
-rw-r--r-- | src/use-sunlight.js | 9 |
1 files changed, 7 insertions, 2 deletions
diff --git a/src/use-sunlight.js b/src/use-sunlight.js index 2ca279b..7a84c3c 100644 --- a/src/use-sunlight.js +++ b/src/use-sunlight.js @@ -1,12 +1,16 @@ import { useState } from 'react' import { useGeolocation as globalUseGeolocation } from './use-geolocation' import { useInterval } from './use-interval' +// TODO roll something smaller since +// this package likely contains tons +// of code we dont need import suncalc from 'suncalc' export const computeLightLevel = ( { loading, latitude, longitude }, date = new Date() ) => { + // assume darkness if info is not ready/available if (loading || !latitude || !longitude) return 0 let { altitude } = suncalc.getPosition(date, latitude, longitude) if (altitude < 0) { @@ -23,10 +27,11 @@ export const computeLightLevel = ( // make a location hook injectable such that we can test this export const useSunlight = (useGeolocation = globalUseGeolocation) => { const geoLocation = useGeolocation() + const getLightLevel = () => computeLightLevel(geoLocation) - const [lightLevel, setLightLevel] = useState(computeLightLevel(geoLocation)) + const [lightLevel, setLightLevel] = useState(getLightLevel()) useInterval(() => { - setLightLevel(computeLightLevel(geoLocation)) + setLightLevel(getLightLevel()) }, 1000) return [lightLevel] } |