diff --git a/weatherfit_refactoring/contexts/WeatherContext.tsx b/weatherfit_refactoring/contexts/WeatherContext.tsx index eee8359..589d046 100644 --- a/weatherfit_refactoring/contexts/WeatherContext.tsx +++ b/weatherfit_refactoring/contexts/WeatherContext.tsx @@ -1,101 +1,109 @@ -import { ReactNode, createContext, useState } from "react"; +'use client' +import { ReactNode, createContext, useEffect, useState } from 'react' interface WeatherProvider { - icon : string | undefined; - tempNow : number | undefined; - tempMax : number | undefined; - tempMin : number | undefined; + icon: string | undefined + tempNow: number | undefined + tempMax: number | undefined + tempMin: number | undefined } -export const WeatherContext = createContext(undefined); +export const WeatherContext = createContext( + undefined, +) -export const WeatherProvider = ({children}: {children: ReactNode}) => { - - const [ temperature, setTemp ] = useState(); - const [ temperatureMin, setTempMin ] = useState(); - const [ temperatureMax, setTempMax ] = useState(); - const [ weatherIcon, setIcon ] = useState(); - const [ latitude_state, setLatitude ] = useState(); - const [ longitude_state, setLongitude ] = useState(); - const [address, setAddress] = useState() +export const WeatherProvider = ({ children }: { children: ReactNode }) => { + const [temperature, setTemp] = useState() + const [temperatureMin, setTempMin] = useState() + const [temperatureMax, setTempMax] = useState() + const [weatherIcon, setIcon] = useState() + const [latitude_state, setLatitude] = useState() + const [longitude_state, setLongitude] = useState() + const [address, setAddress] = useState() - // API Keys - // openweathermap - const API_KEY:string = "e88170b7fa2aeadd4ba37bb1561a53f2" - // KaKao - const KAKAO_API_KEY:string = "3a6c3035c801405eaa71ebb9dc7f474b" + // API Keys + // openweathermap + const API_KEY: string = 'e88170b7fa2aeadd4ba37bb1561a53f2' + // KaKao + const KAKAO_API_KEY: string = '3a6c3035c801405eaa71ebb9dc7f474b' + useEffect(() => { + const getLocation = async () => { + try { + // 위치 노출이 허용되어 있는지 확인하고 현재 위치 가져오기 + const position = await new Promise( + (resolve, reject) => { + navigator.geolocation.getCurrentPosition(resolve, reject) + }, + ) - const getLocation = async() => { - try { - // 위치 노출이 허용되어 있는지 확인하고 현재 위치 가져오기 - const position = await new Promise( - (resolve, reject) => { - navigator.geolocation.getCurrentPosition(resolve, reject) - }, - ); - - // 위도와 경도 가져오기 - setLatitude(position.coords.latitude) - setLongitude(position.coords.longitude) - - } catch (error) { - console.error("Error getting location:", error); - } + // 위도와 경도 가져오기 + setLatitude(position.coords.latitude) + setLongitude(position.coords.longitude) + } catch (error) { + console.error('Error getting location:', error) + } } - const getWeather = async() => { - try { - // OpenWeatherMap에서 위치 기반 날씨 정보 불러오기 - const weatherResponse = await fetch( - `https://api.openweathermap.org/data/2.5/weather?lat=${latitude_state}&lon=${longitude_state}&appid=${API_KEY}&units=metric` - ); - const weatherData = await weatherResponse.json(); - - // 날씨 정보 저장하기 - setTemp(weatherData.main.temp.toFixed(1)); - setTempMax(weatherData.main.temp_max.toFixed(1)); - setTempMin(weatherData.main.temp_min.toFixed(1)); - setIcon(weatherData.weather[0].icon); + getLocation() + }, []) + + useEffect(() => { + const getWeather = async () => { + console.log('위도', latitude_state, '경도', longitude_state) + try { + // OpenWeatherMap에서 위치 기반 날씨 정보 불러오기 + const weatherResponse = await fetch( + `https://api.openweathermap.org/data/2.5/weather?lat=${latitude_state}&lon=${longitude_state}&appid=${API_KEY}&units=metric`, + ) + const weatherData = await weatherResponse.json() - } catch (error) { - console.error("Error getting location:", error); - } + // 날씨 정보 저장하기 + setIcon(weatherData.weather[0].icon) + setTemp(weatherData.main.temp.toFixed(1)) + setTempMax(weatherData.main.temp_max.toFixed(1)) + setTempMin(weatherData.main.temp_min.toFixed(1)) + } catch (error) { + console.error('Error getting location:', error) + } } - const getAddress = async() => { - try { - const addressResponse = await fetch( - `https://dapi.kakao.com/v2/local/geo/coord2address.json?x=${longitude_state}&y=${latitude_state}`, - { - method: "GET", - headers: { Authorization: `KakaoAK ${KAKAO_API_KEY}` } - }, - ); - const addressData = await addressResponse.json(); - setAddress( - addressData.documents[0].address.region_1depth_name + - " " + - addressData.documents[0].address.region_2depth_name, - ); - - } catch (error) { - console.error("Error getting location:", error); - } + if (latitude_state && longitude_state) getWeather() + }, [latitude_state, longitude_state]) + + useEffect(() => { + const getAddress = async () => { + try { + const addressResponse = await fetch( + `https://dapi.kakao.com/v2/local/geo/coord2address.json?x=${longitude_state}&y=${latitude_state}`, + { + method: 'GET', + headers: { Authorization: `KakaoAK ${KAKAO_API_KEY}` }, + }, + ) + const addressData = await addressResponse.json() + setAddress( + addressData.documents[0].address.region_1depth_name + + ' ' + + addressData.documents[0].address.region_2depth_name, + ) + } catch (error) { + console.error('Error getting location:', error) + } } - getLocation(); - getAddress(); - getAddress(); - - return ( - - {children} - - ) -} \ No newline at end of file + if (address) getAddress() + }, [temperatureMin]) + + return ( + + {children} + + ) +} diff --git a/weatherfit_refactoring/src/Components/Molecules/WeatherNavbar.tsx b/weatherfit_refactoring/src/Components/Molecules/WeatherNavbar.tsx index e32f154..1bf101d 100644 --- a/weatherfit_refactoring/src/Components/Molecules/WeatherNavbar.tsx +++ b/weatherfit_refactoring/src/Components/Molecules/WeatherNavbar.tsx @@ -8,7 +8,8 @@ import { WeatherTempMax } from '@/Store/WeatherMaxTemp' import { WeatherTempMin } from '@/Store/WeatherMinTemp' export default function WeatherNavbar() { - const API_KEY = 'fa3eba61f243af3e8e69086462763172' + // const API_KEY = 'fa3eba61f243af3e8e69086462763172' + const API_KEY = 'e88170b7fa2aeadd4ba37bb1561a53f2' const KAKAO_API_KEY = '3a6c3035c801405eaa71ebb9dc7f474b' const { temperature, setTemp } = WeatherTemp() @@ -20,94 +21,56 @@ export default function WeatherNavbar() { const [address, setAddress] = useState() // 렌더링 속도 비교해보기 - // const getLocation = async() => { - // try { - // // 위치 노출이 허용되어 있는지 확인하고 현재 위치 가져오기 - // const position = await new Promise( - // (resolve, reject) => { - // navigator.geolocation.getCurrentPosition(resolve, reject) - // }, - // ); - - // // 위도와 경도 가져오기 - // setLatitude(position.coords.latitude) - // setLongitude(position.coords.longitude) - - // } catch (error) { - // console.error("Error getting location:", error); - // } - // } - - // const getWeather = async() => { - // try { - // // OpenWeatherMap에서 위치 기반 날씨 정보 불러오기 - // const weatherResponse = await fetch( - // `https://api.openweathermap.org/data/2.5/weather?lat=${latitude_state}&lon=${longitude_state}&appid=${API_KEY}&units=metric` - // ); - // const weatherData = await weatherResponse.json(); - - // // 날씨 정보 저장하기 - // setTemp(weatherData.main.temp.toFixed(1)); - // setTempMax(weatherData.main.temp_max.toFixed(1)); - // setTempMin(weatherData.main.temp_min.toFixed(1)); - // setIcon(weatherData.weather[0].icon); - - // } catch (error) { - // console.error("Error getting location:", error); - // } - // } - - // const getAddress = async() => { - // try { - // const addressResponse = await fetch( - // `https://dapi.kakao.com/v2/local/geo/coord2address.json?x=${longitude_state}&y=${latitude_state}`, - // { - // method: "GET", - // headers: { Authorization: `KakaoAK ${KAKAO_API_KEY}` } - // }, - // ); - // const addressData = await addressResponse.json(); - // setAddress( - // addressData.documents[0].address.region_1depth_name + - // " " + - // addressData.documents[0].address.region_2depth_name, - // ); - - // } catch (error) { - // console.error("Error getting location:", error); - // } - // } useEffect(() => { const getLocation = async () => { try { + // 위치 노출이 허용되어 있는지 확인하고 현재 위치 가져오기 const position = await new Promise( (resolve, reject) => { navigator.geolocation.getCurrentPosition(resolve, reject) }, ) - const latitude = position.coords.latitude - // console.log("위도", latitude); - const longitude = position.coords.longitude - // console.log("경도", longitude); + // 위도와 경도 가져오기 + setLatitude(position.coords.latitude) + setLongitude(position.coords.longitude) + } catch (error) { + console.error('Error getting location:', error) + } + } + + getLocation() + }, []) + useEffect(() => { + const getWeather = async () => { + console.log('위도', latitude_state, '경도', longitude_state) + try { + // OpenWeatherMap에서 위치 기반 날씨 정보 불러오기 const weatherResponse = await fetch( - `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`, + `https://api.openweathermap.org/data/2.5/weather?lat=${latitude_state}&lon=${longitude_state}&appid=${API_KEY}&units=metric`, ) const weatherData = await weatherResponse.json() + + // 날씨 정보 저장하기 + setIcon(weatherData.weather[0].icon) setTemp(weatherData.main.temp.toFixed(1)) - // max = weatherData.main.temp_max.toFixed(1); setTempMax(weatherData.main.temp_max.toFixed(1)) setTempMin(weatherData.main.temp_min.toFixed(1)) - // setWeat(weatherData.weather[0].main); - setIcon(weatherData.weather[0].icon) + } catch (error) { + console.error('Error getting location:', error) + } + } - // console.log("데이터", weatherData); - // console.log(`온도 : ${temp} ,최고온도 ${max},최저온도 ${min}, 날씨 : ${weat}`); + if (latitude_state && longitude_state) getWeather() + }, [latitude_state, longitude_state]) + useEffect(() => { + const getAddress = async () => { + try { const addressResponse = await fetch( - `https://dapi.kakao.com/v2/local/geo/coord2address.json?x=${longitude}&y=${latitude}`, + `https://dapi.kakao.com/v2/local/geo/coord2address.json?x=${longitude_state}&y=${latitude_state}`, { method: 'GET', headers: { Authorization: `KakaoAK ${KAKAO_API_KEY}` }, @@ -119,17 +82,13 @@ export default function WeatherNavbar() { ' ' + addressData.documents[0].address.region_2depth_name, ) - - // console.log(address); } catch (error) { console.error('Error getting location:', error) } } - getLocation() - // getWeather(); - // getAddress(); - }, []) + if (address) getAddress() + }, [temperatureMin]) return (
diff --git a/weatherfit_refactoring/src/app/layout.tsx b/weatherfit_refactoring/src/app/layout.tsx index 4c0deb4..3efecc3 100644 --- a/weatherfit_refactoring/src/app/layout.tsx +++ b/weatherfit_refactoring/src/app/layout.tsx @@ -1,6 +1,7 @@ import type { Metadata } from 'next' import ReactQueryProvider from '../utils/provider/ReactQueryProvider' import WebView from '@/Components/WebView/WebView' +import { WeatherProvider } from '../../contexts/WeatherContext' import './globals.css' export const metadata: Metadata = { @@ -17,7 +18,9 @@ export default function RootLayout({ - {children} + + {children} +