Skip to content

Commit

Permalink
Handle 401 errors from open weather
Browse files Browse the repository at this point in the history
  • Loading branch information
jesusoterogomez committed Apr 28, 2020
1 parent 0095784 commit 64d1e7f
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 9 deletions.
2 changes: 1 addition & 1 deletion .env
Original file line number Diff line number Diff line change
@@ -1 +1 @@
INLINE_RUNTIME_CHUNK=false
INLINE_RUNTIME_CHUNK=false
2 changes: 1 addition & 1 deletion src/components/CurrentWeather/CurrentWeather.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import React, { useState, useEffect } from "react";
import { Weather } from "Types";
import { getPosition } from "utils/geolocation";
import { getWeather } from "utils/openweather";
import OpenWeatherIcon from "components/OpenWeatherIcon/OpenWeatherIcon";
import OpenWeatherIcon from "components/OpenWeatherIcon";
import "./CurrentWeather.scss";

import { motion } from "framer-motion";
Expand Down
1 change: 1 addition & 0 deletions src/components/OpenWeatherIcon/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export { default } from "./OpenWeatherIcon";
28 changes: 21 additions & 7 deletions src/utils/openweather.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,15 @@ type QueryParams = {
long?: string | number;
};

// Add REACT_APP_OPEN_WEATHER_API_KEY has to exist in .env.local file.
// The .env.local file is gitignored must be generated during CI executions
// Enter your Open Weather API key in the .env file
const KEY = process.env.REACT_APP_OPEN_WEATHER_API_KEY;

if (!KEY) {
console.error(
"Please add your OpenWeatherMap API Key (https://home.openweathermap.org/api_keys) to the .env file"
);
}

const shouldUseWeatherCache = async () => {
const timestamp = (await getStorage(KEYS.WEATHER_DATA_FETCH_TIMESTAMP)) as
| number
Expand Down Expand Up @@ -67,11 +72,20 @@ export const getWeather = async (query: QueryParams) => {
...query,
});

const response = await fetch(WEATHER_API_URL + params);
const weatherData = (await response.json()) as Weather;
try {
const response = await fetch(WEATHER_API_URL + params);
const weatherData = (await response.json()) as Weather;

await setStorage(KEYS.WEATHER_DATA, weatherData);
await setStorage(KEYS.WEATHER_DATA_FETCH_TIMESTAMP, Date.now());
if (response.status === 401) {
throw weatherData;
}

return weatherData;
await setStorage(KEYS.WEATHER_DATA, weatherData);
await setStorage(KEYS.WEATHER_DATA_FETCH_TIMESTAMP, Date.now());

return weatherData;
} catch (e) {
console.error(e);
return null;
}
};

0 comments on commit 64d1e7f

Please sign in to comment.