I'm following a tutorial for a react weather app. I get the API from openweathermap (it works) and still i'm getting this error.
Also I'm getting this (I don't know if it's related) SyntaxError: Unexpected token 'Y', "You need t"... is not valid JSON at JSON.parse (<anonymous>) at window.onload
Clearly this tutorial is over my knowledge (the API/JSON part) but I just want to understand wat's happening to finish it.
The error is thrown in the fetch line:
import { DateTime } from 'luxon'
const API_KEY = 'MY API'
const BASE_URL = 'https://api.openweathermap.org/data/2.5'
const getWeatherData = (infoType, searchParams) => {
const url = new URL(BASE_URL + '/' + infoType)
url.search = new URLSearchParams({ ...searchParams, appid: API_KEY })
HERE IS THE ERROR --->return fetch(url).then((res) => res.json()) <---HERE IS THE ERROR
}
const formatCurrentWeather = (data) => {
const {
coord: { lat, lon },
main: { temp, feels_like, temp_min, temp_max, humidity },
name,
dt,
sys: { country, sunrise, sunset },
weather,
wind: { speed },
} = data
const { main: details, icon } = weather[0]
return {
lat,
lon,
temp,
feels_like,
temp_min,
temp_max,
humidity,
name,
dt,
country,
sunrise,
sunset,
details,
icon,
speed,
}
}
const formatForecastWeather = (data) => {
let { timezone, daily, hourly } = data
daily = daily.slice(1, 6).map((d) => {
return {
title: formatToLocalTime(d.dt, timezone, 'ccc'),
temp: d.temp.day,
icon: d.weather[0].icon,
}
})
hourly = hourly.slice(1, 6).map((d) => {
return {
title: formatToLocalTime(d.dt, timezone, 'hh:mm a'),
temp: d.temp,
icon: d.weather[0].icon,
}
})
return { timezone, daily, hourly }
}
const getFormattedWeatherData = async (searchParams) => {
const formattedCurrentWeather = await getWeatherData(
'weather',
searchParams,
).then(formatCurrentWeather)
const { lat, lon } = formattedCurrentWeather
const formattedForecastWeather = await getWeatherData('onecall', {
lat,
lon,
exclude: 'current,minutely,alerts',
units: searchParams.units,
}).then(formatForecastWeather)
return { ...formattedCurrentWeather, ...formattedForecastWeather }
}
const formatToLocalTime = (
secs,
zone,
format = "cccc, dd LLL yyyy' | Local time: 'hh:mm a",
) => DateTime.fromSeconds(secs).setZone(zone).toFormat(format)
const iconUrlFromCode = (code) =>
`http://openweathermap.org/img/wn/${code}@2x.png`
export default getFormattedWeatherData
export { formatToLocalTime, iconUrlFromCode }
Thanks!
I just want to understand why it is happening this when that is no what happens in the tutorial i'm seeing.