1. API키 발급
Current weather and forecast - OpenWeatherMap
OpenWeather Weather forecasts, nowcasts and history in a fast and elegant way
openweathermap.org
2. 배열타입을 지정한다
type SeoulWeatherType = {
weather:Array<
{
id:number
main:string
description:string
icon:string
}
>
}
3. fetch함수로 api통신, 이때 json()타입이 any타입이므로 SeoulWeatherType으로 타입어선셜(타입을 정확히 알려줌)

const fetchWeather = async() =>{
const res = await fetch(`https://api.openweathermap.org/data/2.5/weather?q=Seoul&appid=API_KEY`)
if(res.ok) {
return await res.json() as SeoulWeatherType
}
throw new Error(res.statusText)
}
4.useQuery타입에는 data프로퍼티 타입하고, 에러타입이 있다. 쿼리키는 'weather' 로 지정했다
export default function QueryWeather(){
const {data,isLoading,isError,error} = useQuery<SeoulWeatherType,Error>("weather", fetchWeather)
// 로딩표시
if(isLoading) {
return <h2>로딩중</h2>
}
// 에러를 화면에 메세지를보여준다
if(isError) {
return <h2>에러내용: {error.message}</h2>
}
return (
<figure>
<img src={`https://openweathermap.org/img/wn/${data?.weather?.[0]?.icon}.png`} alt="{data?.weather?.[0]?.main}" />
<figcaption>{data?.weather?.[0]?.description}</figcaption>
</figure>
)
}
5. React QueryClient 객체 생성후 객체안에 Suspense를 사용하려면 defaultOptions queries에 옵션을 true로 활성화
// Suspense 모드 활성화
const cli = new QueryClient({
defaultOptions:{
queries:{
suspense:true
}
}
})
6. 코드 변환
// Suspense를 사용해 제거
// if(isLoading) {
// return <h2>로딩중</h2>
// }
// if(isError) {
// return <h2>에러내용: {error.message}</h2>
// }
root.render(
<Suspense fallback={<h2>로딩중</h2>}>
<ErrorBoundary fallback={<h2>에러발생</h2>}>
<QueryClientProvider client={cli}>
<QueryBasic />
</QueryClientProvider>
</ErrorBoundary>
</Suspense>
);
7. 결과화면
참고한 책입니다
https://www.yes24.com/Product/Goods/134020954
따라하며 쉽게 배우는 모던 리액트 완벽 입문 - 예스24
모던 자바스크립트, 타입스크립트, Next.js로 만드는 본격적인 앱 개발을 위한 종합 안내서!이 책은 리액트를 처음 배우는 사람들을 위한 입문서로, 자바스크립트 기본 지식을 가진 독자를 대상으
www.yes24.com