Skip to content

Commit

Permalink
Merge pull request kdt-8-4#85 from kdt-8-4/performanceimprove
Browse files Browse the repository at this point in the history
[Fix] 피드 페이지 날씨 바 로직 개선 PerformanceImprove kdt-8-4#82 Feed kdt-8-4#7
  • Loading branch information
nebulaBdj authored Apr 2, 2024
2 parents 6a2f265 + 1b30e5e commit 64d8939
Show file tree
Hide file tree
Showing 3 changed files with 132 additions and 162 deletions.
180 changes: 94 additions & 86 deletions weatherfit_refactoring/contexts/WeatherContext.tsx
Original file line number Diff line number Diff line change
@@ -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<WeatherProvider | undefined>(undefined);
export const WeatherContext = createContext<WeatherProvider | undefined>(
undefined,
)

export const WeatherProvider = ({children}: {children: ReactNode}) => {

const [ temperature, setTemp ] = useState<number>();
const [ temperatureMin, setTempMin ] = useState<number>();
const [ temperatureMax, setTempMax ] = useState<number>();
const [ weatherIcon, setIcon ] = useState<string>();
const [ latitude_state, setLatitude ] = useState<number>();
const [ longitude_state, setLongitude ] = useState<number>();
const [address, setAddress] = useState<string | undefined>()
export const WeatherProvider = ({ children }: { children: ReactNode }) => {
const [temperature, setTemp] = useState<number>()
const [temperatureMin, setTempMin] = useState<number>()
const [temperatureMax, setTempMax] = useState<number>()
const [weatherIcon, setIcon] = useState<string>()
const [latitude_state, setLatitude] = useState<number>()
const [longitude_state, setLongitude] = useState<number>()
const [address, setAddress] = useState<string | undefined>()

// 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<GeolocationPosition>(
(resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject)
},
)

const getLocation = async() => {
try {
// 위치 노출이 허용되어 있는지 확인하고 현재 위치 가져오기
const position = await new Promise<GeolocationPosition>(
(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 (
<WeatherContext.Provider value={{
icon : weatherIcon,
tempMax : temperatureMax,
tempMin : temperatureMin,
tempNow : temperature
}}>
{children}
</WeatherContext.Provider>
)
}
if (address) getAddress()
}, [temperatureMin])

return (
<WeatherContext.Provider
value={{
icon: weatherIcon,
tempMax: temperatureMax,
tempMin: temperatureMin,
tempNow: temperature,
}}>
{children}
</WeatherContext.Provider>
)
}
109 changes: 34 additions & 75 deletions weatherfit_refactoring/src/Components/Molecules/WeatherNavbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -20,94 +21,56 @@ export default function WeatherNavbar() {
const [address, setAddress] = useState<string | undefined>()

// 렌더링 속도 비교해보기
// const getLocation = async() => {
// try {
// // 위치 노출이 허용되어 있는지 확인하고 현재 위치 가져오기
// const position = await new Promise<GeolocationPosition>(
// (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<GeolocationPosition>(
(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}` },
Expand All @@ -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 (
<article className="flex justify-between items-center text-[12px] border-t border-b border-slate-100 px-2">
Expand Down
5 changes: 4 additions & 1 deletion weatherfit_refactoring/src/app/layout.tsx
Original file line number Diff line number Diff line change
@@ -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 = {
Expand All @@ -17,7 +18,9 @@ export default function RootLayout({
<html lang="ko">
<body>
<ReactQueryProvider>
<WebView>{children}</WebView>
<WebView>
<WeatherProvider>{children}</WeatherProvider>
</WebView>
</ReactQueryProvider>
</body>
</html>
Expand Down

0 comments on commit 64d8939

Please sign in to comment.