Skip to content

Instantly share code, notes, and snippets.

@yonibot
Created November 18, 2019 19:24
Show Gist options
  • Save yonibot/f58affe7db5ecf808aaee7a069d2c3bc to your computer and use it in GitHub Desktop.
Save yonibot/f58affe7db5ecf808aaee7a069d2c3bc to your computer and use it in GitHub Desktop.

Revisions

  1. yonibot created this gist Nov 18, 2019.
    50 changes: 50 additions & 0 deletions App.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,50 @@
    // App.js

    import { useWeatherService } from './useWeatherService';
    ...

    function App({coords}) {

    const [ currentUnit, setUnit ] = useState(TEMPERATURE_UNITS.metric);
    const [ weather, getWeather ] = useWeatherService(); // <- initializing the hook

    useEffect(() => {
    if (coords) {
    const { latitude: lat, longitude: lon } = coords;
    getWeather(lat, lon, currentUnit.sysName); // <- calling the hook
    }
    }, [coords, currentUnit]);

    ...

    return (
    <div className="App">
    ...
    </div>
    );
    }

    export default geolocated()(App);




    // useWeatherService.js

    import { useState } from 'react';

    const useWeatherService = () => {
    const [weather, setWeather] = useState();

    const getWeather = async (lat, long, unit) => {
    const weatherReq = await fetch(/* apiUrl */);
    ...
    ...
    setWeather(weather);
    }

    return [ weather, getWeather ];
    }

    export { useWeatherService }