[ReactNative] Expo 날씨(expo-location) 서버 외부 API 사용 방법(2) - 서버가 제공하는 도메인 사용

민지·2021년 11월 27일
0

ReactNative

목록 보기
11/14

날씨 앱 API 공식문서

서버가 제공하는 도메인 형식의 API를 사용하려면, 주소를 실행시키기 위한 도구가 필요하다. 가장 많이 쓰이고 일반적인 axios 라는 도메인 요청 방식의 도구를 설치해주겠다.

도구 설치

yarn add axios

weather API 외부 서비스를 이용하려면 사이트에 회원가입을 하고 해당 API 키를 발급 받아야 서비스를 이용할 수 있게 된다.

파일에서
axios 임포트 해주고

import axios from "axios"
//날씨 데이터 상태관리 생성, 초기화
const [weather, setWeather] = useState({
temp : 0,
condition : ''
})

//위도 경도를 적극적으로 활용하려고 변수에 담음 
const latitude = locationData['coords']['latitude']
const longitude = locationData['coords']['longitude']

const API_KEY = "발급받은 API 키 입력";

//get은 브라우저 주소에서 데이터를 바로 받아서 변수에 담음
const result = await axios.get(
`http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`
);

console.log(result)
const temp = result.data.main.temp; 
const condition = result.data.weather[0].main

console.log(temp)
console.log(condition)

//객체 리터럴 방식으로 딕셔너리 구성
setWeather({
temp,condition
})
//weather라는 상태 값에서 condition과 temp를 바인딩 해줘야 날씨가 반영되게 됨
<Text style={styles.weather}>오늘의 날씨: {weather.temp + '°C ' + weather.condition} </Text>

앱 화면이 바뀌려면 무조건 상태 관리가 필요하다고 보면 된다.
화면이 그려지고 컴포넌트 안에 상태 관리를 통해 데이터가 준비 되면 그 데이터가 앱 화면에 다시 그려지게 되는거다.

profile
개발일지

0개의 댓글