### Environment Configuration: API Keys and Settings (Bash/TypeScript)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
Manages application configuration through environment variables, primarily for API keys. Uses Vite's `import.meta.env` for accessing variables defined in `.env.local` files. Includes settings for weather API, base URL, and optional Kakao API key.
```bash
# .env.local configuration
VITE_WEATHER_API_KEY=your_openweathermap_api_key
VITE_WEATHER_BASE_URL=https://api.openweathermap.org/data/2.5
VITE_KAKAO_API_KEY=your_kakao_api_key # Optional, for detailed Korean addresses
```
```typescript
// src/config/constants.ts - Configuration exports
export const WEATHER_API_KEY = import.meta.env.VITE_WEATHER_API_KEY;
export const WEATHER_BASE_URL = import.meta.env.VITE_WEATHER_BASE_URL;
export const KAKAO_API_KEY = import.meta.env.VITE_KAKAO_API_KEY;
export const MAX_FAVORITES = 6;
export const GEOLOCATION_TIMEOUT = 5000;
export const DEFAULT_LOCATION = {
lat: 37.5665,
lon: 126.9780,
name: '서울특별시',
};
```
--------------------------------
### Application Routes: Navigation with React Router DOM (TypeScript/React)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
Defines the routing structure for the application using React Router DOM. It includes a main dashboard route and a dynamic route for detailed location views. Demonstrates route configuration, navigation using `useNavigate`, and parameter access with `useParams`.
```typescript
import { BrowserRouter as Router, Routes, Route, useNavigate, useParams } from 'react-router-dom';
// App.tsx - Route configuration
function App() {
return (
} />
} />
);
}
// Navigation to detail page
function FavoriteItem({ favorite }) {
const navigate = useNavigate();
return (
);
}
// Accessing route params in detail page
function DetailPage() {
const { locationId } = useParams<{ locationId: string }>();
const { favorites } = useFavorites();
const favorite = favorites.find(f => f.id === locationId);
// ...
}
```
--------------------------------
### Weather Helper Functions: Suggestions and Calculations (TypeScript)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
Provides utility functions for weather-related tasks. Includes generating Korean-language weather advice based on current conditions and calculating daily minimum and maximum temperatures from hourly forecast data. Requires weatherData and hourlyData as input.
```typescript
import { getWeatherSuggestion, calculateDailyMinMax } from '@/features/shared/utils/weather-helpers';
// Get weather suggestion based on conditions
const suggestion = getWeatherSuggestion(weatherData);
// Returns suggestions like:
// - "비가 오고 있어요. 외출 시 우산을 챙기세요! ☂️"
// - "눈이 내리고 있습니다. 길이 미끄러우니 주의하세요. ❄️"
// - "날씨가 꽤 춥습니다. 따뜻한 옷차림으로 체온을 유지하세요. 🧣" (temp < 5°C)
// - "무더운 날씨입니다. 충분한 수분을 섭취하고 휴식을 취하세요. ☀️" (temp > 28°C)
// - "맑고 쾌적한 날씨입니다. 기분 좋은 하루 보내세요! 😊"
// Calculate daily min/max from hourly forecast
const dailyMinMax = calculateDailyMinMax(hourlyData);
// Returns: { min: 18, max: 26 } for today's temperature range
// Returns: null if no data available
```
--------------------------------
### Formatting Utilities: Temperature and Time Display (TypeScript)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
Offers helper functions for consistent formatting of temperature and time data. `formatTemperature` adds the degree symbol, and `formatHour` displays time in a user-friendly format, including a special case for the current hour. Accepts temperature values and timestamps.
```typescript
import { formatTemperature, formatHour } from '@/features/shared/utils/formatters';
// Format temperature with degree symbol
formatTemperature(23.7); // Returns: "24°"
formatTemperature(-5.2); // Returns: "-5°"
// Format hour for hourly forecast display
formatHour(1704067200, 0); // Returns: "지금" (index 0 = current time)
formatHour(1704078000, 1); // Returns: "15시" (extracts hour from timestamp)
formatHour(1704088800, 2); // Returns: "18시"
```
--------------------------------
### OpenWeatherMap 5-Day Forecast API
Source: https://github.com/doy00/weather-with-duduzi/blob/main/README.md
Retrieves a 5-day weather forecast for a specified location, including hourly predictions. Supports metric units and Korean language.
```APIDOC
## GET /forecast
### Description
Fetches a 5-day weather forecast with hourly predictions for a given latitude and longitude. Includes temperature, icons, and other relevant data.
### Method
GET
### Endpoint
/forecast
### Parameters
#### Query Parameters
- **lat** (number) - Required - The latitude of the location.
- **lon** (number) - Required - The longitude of the location.
- **units** (string) - Optional - Unit of measurement. Defaults to 'metric'.
- **lang** (string) - Optional - Language for the forecast description. Defaults to 'kr'.
- **appid** (string) - Required - Your OpenWeatherMap API key.
### Request Example
```
GET /forecast?lat=37.5665&lon=126.9780&units=metric&lang=kr&appid=your_api_key_here
```
### Response
#### Success Response (200)
- **list** (array) - An array of forecast data objects, each representing a 3-hour interval.
- **city** (object) - Information about the city for which the forecast is provided.
#### Response Example
```json
{
"cod": "200",
"message": 0,
"cnt": 40,
"list": [
{
"dt": 1678886400,
"main": {
"temp": 15.5,
"feels_like": 17.0,
"temp_min": 14.0,
"temp_max": 17.0,
"pressure": 1015,
"sea_level": 1015,
"grnd_level": 1000,
"humidity": 70,
"temp_kf": 3.0
},
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "구름 조금",
"icon": "02d"
}
],
""deg": 200,
"wind_speed": 5.5,
""gust": 8.0,
""cloud": 20,
""pop": 0.2
}
// ... more forecast entries
],
"city": {
"id": 1835848,
"name": "Seoul",
"coord": {
"lat": 37.5665,
"lon": 126.978
},
"country": "KR",
"population": 0,
"timezone": 32400,
"sunrise": 1678857600,
"sunset": 1678899600
}
}
```
```
--------------------------------
### Fetch Hourly Forecast Data with useHourlyForecast Hook (TypeScript)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
This TanStack Query hook fetches hourly forecast data, providing up to 40 data points for a 5-day period at 3-hour intervals. It's designed for displaying hourly weather and calculating daily minimum and maximum temperatures. The hook integrates with utility functions for data processing.
```typescript
import { useHourlyForecast } from '@/features/weather/hooks/useHourlyForecast';
import { calculateDailyMinMax } from '@/features/shared/utils/weather-helpers';
function HourlyDisplay({ lat, lon }: { lat: number; lon: number }) {
const { data: hourly, isLoading, isError } = useHourlyForecast(lat, lon);
if (!hourly) return null;
// Calculate today's min/max from hourly data
const dailyMinMax = calculateDailyMinMax(hourly);
return (
);
}
```
--------------------------------
### Batch Fetch Weather for Favorites with useFavoriteWeather Hook (TypeScript)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
Leveraging TanStack Query, the `useFavoriteWeather` hook efficiently fetches weather data for all favorite locations concurrently. It utilizes `useQueries` to manage multiple asynchronous requests and employs a 5-minute stale time for effective data caching. The hook takes an array of favorite locations and returns an array of query results, each containing weather data, loading state, and error information.
```typescript
import { useFavorites } from '@/features/favorites/hooks/useFavorites';
import { useFavoriteWeather } from '@/features/favorites/hooks/useFavoriteWeather';
function FavoritesWeatherDisplay() {
const { favorites } = useFavorites();
const weatherResults = useFavoriteWeather(favorites);
// weatherResults is an array of UseQueryResult objects, one per favorite
// Each result has: { data, isLoading, isError, error }
return (
{fav.nickname || fav.name}
{isLoading ? (
Loading...
) : weather ? (
{Math.round(weather.main.temp)}°
) : (
No data
)}
);
})}
);
}
```
--------------------------------
### Dynamic Backgrounds with useTimeBasedBackground Hook (TypeScript)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
The `useTimeBasedBackground` hook dynamically generates Tailwind CSS gradient classes based on the current time of day. This hook automatically updates every minute to ensure the background reflects the appropriate time period (morning, day, evening, night). It returns the relevant gradient classes and the current time period identifier.
```typescript
import { useTimeBasedBackground } from '@/features/shared/hooks/useTimeBasedBackground';
function TimeBasedLayout({ children }: { children: React.ReactNode }) {
const { gradientClasses, timePeriod } = useTimeBasedBackground();
// gradientClasses: Tailwind gradient classes like "from-blue-900 to-blue-600"
// timePeriod: 'morning' | 'day' | 'evening' | 'night'
// Updates automatically every minute when time period changes
return (
{children}
);
}
```
--------------------------------
### Fetch Weather Data using Weather Service API (TypeScript)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
Provides functions to fetch current weather, hourly forecasts, and location coordinates using the OpenWeatherMap API. It includes geocoding and reverse geocoding capabilities, with a fallback to Kakao API for detailed addresses. Error handling for API responses is managed within these functions.
```typescript
import { fetchCurrentWeather, fetchHourlyWeather, geocodeLocation, reverseGeocode } from '@/features/weather/services/weatherService';
// Fetch current weather for coordinates (Seoul example)
const currentWeather = await fetchCurrentWeather(37.5665, 126.9780);
// Returns: { coord, weather: [{ main, description, icon }], main: { temp, temp_min, temp_max, feels_like, humidity }, name, dt }
// Fetch 5-day / 3-hour forecast
const forecast = await fetchHourlyWeather(37.5665, 126.9780);
// Returns: { list: [{ dt, main: { temp }, weather: [{ icon }] }] }
// Geocode a location name to coordinates
const results = await geocodeLocation('서울');
// Returns: [{ lat: 37.5665, lon: 126.9780, name: '서울' }]
// Reverse geocode coordinates to location name (uses Kakao API with OpenWeatherMap fallback)
const locationName = await reverseGeocode(37.5665, 126.9780);
// Returns: '서울특별시 중구 명동' (detailed address from Kakao API)
```
--------------------------------
### OpenWeatherMap Current Weather API
Source: https://github.com/doy00/weather-with-duduzi/blob/main/README.md
Fetches current weather data for a specified location using latitude and longitude. Supports metric units and Korean language.
```APIDOC
## GET /weather
### Description
Fetches current weather conditions including temperature, min/max temperature, and a weather description for a given latitude and longitude.
### Method
GET
### Endpoint
/weather
### Parameters
#### Query Parameters
- **lat** (number) - Required - The latitude of the location.
- **lon** (number) - Required - The longitude of the location.
- **units** (string) - Optional - Unit of measurement. Defaults to 'metric'.
- **lang** (string) - Optional - Language for the weather description. Defaults to 'kr'.
- **appid** (string) - Required - Your OpenWeatherMap API key.
### Request Example
```
GET /weather?lat=37.5665&lon=126.9780&units=metric&lang=kr&appid=your_api_key_here
```
### Response
#### Success Response (200)
- **main** (object) - Contains main weather parameters like temperature, humidity, etc.
- **weather** (array) - Contains weather condition details.
- **name** (string) - City name.
#### Response Example
```json
{
"coord": {
"lon": 126.978,
"lat": 37.5665
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "맑음",
"icon": "01d"
}
],
"main": {
"temp": 25.5,
"feels_like": 27.0,
"temp_min": 23.0,
"temp_max": 28.0,
"pressure": 1012,
"humidity": 60
},
"name": "Seoul"
}
```
```
--------------------------------
### Manage Favorite Locations with useFavorites Hook (TypeScript)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
The `useFavorites` hook facilitates the management of favorite locations, with persistence handled via `localStorage`. It supports operations such as adding, removing, updating nicknames, and checking the favorite status of a location. The hook enforces a limit of 6 favorite locations and returns the current list of favorites along with the management functions.
```typescript
import { useFavorites } from '@/features/favorites/hooks/useFavorites';
function FavoritesManager() {
const { favorites, addFavorite, removeFavorite, updateNickname, isFavorite } = useFavorites();
// Add a new favorite (max 6)
const handleAdd = () => {
try {
addFavorite({
id: '', // Auto-generated from Date.now()
fullName: '서울특별시-종로구-청운동',
name: '청운동',
lat: 37.5847,
lon: 126.9706,
});
} catch (error) {
// Throws: "즐겨찾기는 최대 6개까지 가능합니다."
alert(error.message);
}
};
// Check if location is favorited
const isFav = isFavorite('서울특별시-종로구-청운동');
// Update nickname
updateNickname('favorite-id', '우리집');
// Remove favorite
removeFavorite('favorite-id');
return (
{favorites.map((fav) => (
{fav.nickname || fav.name}
))}
);
}
```
--------------------------------
### Fetch and Cache Current Weather Data with useWeatherData Hook (TypeScript)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
A TanStack Query hook for fetching and caching current weather data based on latitude and longitude. It exposes loading and error states, and provides a refetch function with automatic retry capabilities. This hook simplifies integrating real-time weather information into React components.
```typescript
import { useWeatherData } from '@/features/weather/hooks/useWeatherData';
function WeatherComponent({ lat, lon }: { lat: number; lon: number }) {
const { data, isLoading, isError, error, refetch } = useWeatherData(lat, lon);
if (isLoading) return
Loading weather...
;
if (isError) return ;
return (
Temperature: {Math.round(data.main.temp)}°C
Condition: {data.weather[0].description}
Humidity: {data.main.humidity}%
);
}
```
--------------------------------
### GlassCard Component: Reusable UI Element (TypeScript/React)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
A flexible and visually appealing glassmorphism card component. It supports custom styling, click handling, and serves as a primary container for displaying information. Built with React.
```typescript
import { GlassCard } from '@/features/shared/components/GlassCard';
function WeatherCard() {
return (
console.log('Card clicked')}
>
Weather Details
Current temperature: 24°
);
}
// GlassCard applies: glass rounded-3xl p-6 mb-4 transition-all duration-300
// With onClick: adds cursor-pointer active:scale-95
```
--------------------------------
### Geocode Location Names with useGeocode Hook (TypeScript)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
The `useGeocode` hook offers a geocoding function that converts location names into geographical coordinates using the OpenWeatherMap Geocoding API. It is specifically tailored to return the first matching result for Korean locations. The hook returns an object containing latitude, longitude, and the location name, or throws an error if the location is not found.
```typescript
import { useGeocode } from '@/features/location/hooks/useGeocode';
function GeocodingComponent() {
const { geocode } = useGeocode();
const handleSelectLocation = async (locationName: string) => {
try {
const result = await geocode('청운동');
// Returns: { lat: 37.5847, lon: 126.9706, name: '청운동' }
console.log(`Coordinates: ${result.lat}, ${result.lon}`);
} catch (error) {
// Throws: "해당 장소의 정보가 제공되지 않습니다." if not found
console.error(error.message);
}
};
return ;
}
```
--------------------------------
### Handle Browser Geolocation with useGeolocation Hook (TypeScript)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
A React hook that manages browser geolocation requests, including configurable timeouts and an automatic fallback to Seoul's coordinates if the request fails. It provides loading states and status messages for user feedback, and returns coordinates or null if unavailable. Error handling for unsupported browsers is also included.
```typescript
import { useGeolocation } from '@/features/location/hooks/useGeolocation';
function LocationAwareComponent() {
const { coords, isLoading, error, locationStatus } = useGeolocation();
// coords: { lat: number, lon: number } | null
// locationStatus: "위치 정보 확인 중..." | "사용자 위치를 파악하고 있습니다..." | ""
// error: string | null (e.g., "브라우저가 위치 정보를 지원하지 않습니다.")
if (isLoading) return
{locationStatus}
;
// Falls back to Seoul (37.5665, 126.9780) if geolocation fails
return (
Latitude: {coords?.lat}
Longitude: {coords?.lon}
);
}
```
--------------------------------
### Filter Korean Regions with useLocationSearch Hook (TypeScript)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
The `useLocationSearch` hook provides a memoized function for filtering Korean region names from a predefined list. It performs case-insensitive matching and is designed for autocomplete functionality, returning up to 15 results. It takes a query string as input and returns an array of matching region strings.
```typescript
import { useLocationSearch } from '@/features/location/hooks/useLocationSearch';
function LocationSearchComponent() {
const [query, setQuery] = useState('');
const results = useLocationSearch(query);
// Example: query = '서울' returns ['서울특별시-종로구-청운동', '서울특별시-중구-명동', ...]
// Results are filtered from 150+ Korean regions
return (
setQuery(e.target.value)} />
{results.map((location) => (
{location}
))}
);
}
```
--------------------------------
### OpenWeatherMap Geocoding API
Source: https://github.com/doy00/weather-with-duduzi/blob/main/README.md
Converts location names into geographic coordinates (latitude and longitude). Useful for searching locations within South Korea.
```APIDOC
## GET /geo/1.0/direct
### Description
Converts a location name (city) to geographic coordinates (latitude and longitude). This endpoint is used for searching Korean regions and popular cities.
### Method
GET
### Endpoint
/geo/1.0/direct
### Parameters
#### Query Parameters
- **q** (string) - Required - The location name (e.g., "Seoul,KR").
- **limit** (integer) - Optional - The number of locations to return. Defaults to 5.
- **appid** (string) - Required - Your OpenWeatherMap API key.
### Request Example
```
GET /geo/1.0/direct?q=Seoul,KR&limit=5&appid=your_api_key_here
```
### Response
#### Success Response (200)
- **[ ]** (array) - An array of location objects, each containing latitude, longitude, name, country, state, and potentially other details.
#### Response Example
```json
[
{
"name": "Seoul",
"lat": 37.566535,
"lon": 126.977969,
"country": "KR",
"state": "Seoul"
}
]
```
```
--------------------------------
### ErrorBoundary Component: Production Error Handling (TypeScript/React)
Source: https://context7.com/doy00/weather-with-duduzi/llms.txt
A React class component designed to gracefully handle JavaScript errors within its child component tree. It displays a fallback UI and provides a reload mechanism for user-friendly error management in production environments.
```typescript
import { ErrorBoundary } from '@/features/shared/components/ErrorBoundary';
function App() {
return (
} />
} />
);
}
// On error, displays:
// - Error icon
// - "예상치 못한 오류가 발생했습니다." message
// - Error details
// - "다시 로드" button that reloads the page
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.