Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,12 @@
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"preview": "vite preview"
"preview": "vite preview",
"fmt": "npx prettier . --write"
},
"dependencies": {
"@tanstack/react-query": "^5.102.8",
"country-codes-list": "^3.2.0",
"react": "^19.2.8",
"react-dom": "^19.2.8"
},
Expand Down
1 change: 0 additions & 1 deletion src/App.css
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,6 @@
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;

@media (max-width: 1024px) {
Expand Down
2 changes: 1 addition & 1 deletion src/components/listItem.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
type cityWeather = {
name: string
name?: string
temperature?: number
precipitation?: number
nextDays?: { time: string; temperature: number | undefined }[]
Expand Down
39 changes: 14 additions & 25 deletions src/components/location-list.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,7 @@
import type { WeatherApiResponse } from "../hooks/fetchWeather/types"
import useGetWeather from "../hooks/fetchWeather/useGetWeather"
import type { WeatherApiResponse, City } from "../hooks/fetchWeather/types"
import { useGetWeatherForCities } from "../hooks/fetchWeather/useGetWeather"
import ListItem from "./listItem"

type City = {
name: string
lat: number
lon: number
}

const cities: City[] = [
{ name: "Oslo", lat: 59.91273, lon: 10.74609 },
{ name: "Sørumsand", lat: 59.98621, lon: 11.24154 },
Expand All @@ -31,7 +25,12 @@ const getNextDays = (data?: WeatherApiResponse) => {
return (
date >= now &&
date.getUTCHours() === 12 &&
date < new Date(now.getTime() + 3 * 24 * 60 * 60 * 1000)
date <
new Date(
now.getTime() -
now.getHours() * 60 * 60 * 1000 +
4 * 24 * 60 * 60 * 1000
)
)
})
.map((entry) => ({
Expand All @@ -43,23 +42,17 @@ const getNextDays = (data?: WeatherApiResponse) => {
}

const LocationList = () => {
const weatherResults = cities.map((city) => useGetWeather(city.lat, city.lon))

console.log(weatherResults)

if (weatherResults.some((result) => result.isLoading)) {
return <div>Loading weather…</div>
}
const { isLoading, results } = useGetWeatherForCities(cities)

if (weatherResults.some((result) => result.error)) {
return <div>Could not load weather data.</div>
if (isLoading) {
return <div>Loading...</div>
}

const cityWeather = cities.map((city, index) => ({
name: city.name,
temperature: getTemperature(weatherResults[index]?.result),
precipitation: getPrecipitation(weatherResults[index]?.result),
nextDays: getNextDays(weatherResults[index]?.result),
temperature: getTemperature(results[index]),
precipitation: getPrecipitation(results[index]),
nextDays: getNextDays(results[index]),
}))

return (
Expand Down Expand Up @@ -98,10 +91,6 @@ const LocationList = () => {
>
{cityWeather.map((item) => (
<ListItem key={item.name} city={item} />
// <li key={item.name}>
// {item.name}: {typeof item.temperature === 'number' ? `${item.temperature}°` : '—'}
// {typeof item.precipitation === 'number' ? `, ${item.precipitation} mm` : ''}
// </li>
))}
</ul>
</div>
Expand Down
7 changes: 7 additions & 0 deletions src/hooks/fetchWeather/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,4 +175,11 @@ export type METJSONForecast = {
type: "Feature"
}

export type City = {
name?: string
lat: number
lon: number
alt?: number
}

export type WeatherApiResponse = METJSONForecast
47 changes: 38 additions & 9 deletions src/hooks/fetchWeather/useGetWeather.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { useQuery } from "@tanstack/react-query"
import { type WeatherApiResponse } from "./types"
import { useQuery, useQueries } from "@tanstack/react-query"
import { type City, type WeatherApiResponse } from "./types"

const useGetWeather = (lat: number, lon: number, alt?: number) => {
let sanitized_alt = alt
if (alt != undefined) {
sanitized_alt = alt > 9000 ? 9000 : alt
sanitized_alt = sanitized_alt < -500 ? -500 : sanitized_alt
}
const sanitizeAltitude = (alt?: number) => {
if (alt === undefined) return undefined
return Math.min(9000, Math.max(-500, alt))
}

export const useGetWeather = (lat: number, lon: number, alt?: number) => {
const sanitized_alt = sanitizeAltitude(alt)

const { isLoading, error, data } = useQuery({
queryKey: ["citySearch", `${lat}-${lon}`],
Expand All @@ -18,5 +19,33 @@ const useGetWeather = (lat: number, lon: number, alt?: number) => {

return { isLoading, error, result: data }
}

export default useGetWeather

const fetchWeather = (
lat: number,
lon: number,
alt?: number
): Promise<WeatherApiResponse> => {
const sanitizedAlt = sanitizeAltitude(alt)
const url = `https://api.met.no/weatherapi/locationforecast/2.0/compact?lat=${lat}&lon=${lon}${
sanitizedAlt !== undefined ? `&altitude=${sanitizedAlt}` : ""
}`
return fetch(url).then((res) => res.json() as Promise<WeatherApiResponse>)
}

export const useGetWeatherForCities = (cities: City[]) => {
const queries = useQueries({
queries: cities.map((city) => ({
queryKey: ["citySearch", `${city.lat}-${city.lon}`],
queryFn: () => fetchWeather(city.lat, city.lon, city.alt),
})),
})

const isLoading = queries.some((q) => q.isLoading)
const errors = queries.filter((q) => q.error).map((q) => q.error)
const results = queries
.map((q) => q.data)
.filter((d): d is WeatherApiResponse => d !== undefined)

return { isLoading, errors, results }
}