[수업 6월 5주 4일차] React-5

김유민·2022년 6월 30일
0

대구 A.I. 스쿨

목록 보기
54/90

1. 학습내용

오늘도 계속해서 실습을 해보았다.
날씨 관련 API를 가져와 날씨 앱을 만들어 보기로 했다.

구현 하기
1. 앱이 실행되자마자 현재위치 기반의 날씨가 보인다.
2. 날씨정보에는 도시, 섭씨, 화씨, 날씨상태
3. 5개의 버튼이 있다.(1개는 현재위치, 4개는 다른도시)
4. 도시버튼을 클릭할 때마다 도시별 날씨가 나온다.
5. 현재위치 버튼을 누르면 다시 현재위치 기반의 날씨가 나온다.
6. 데이터를 들고오는 동안 로딩 스피너가 돈다.

동기와 비동기
• 동기

  • 작업(task)들이 순차적으로 이루어 지는 것
  • 다른 작업들을 blocking
    • 비동기
  • 작업(task)들이 순차적으로 이루어지지 않음
  • 다른 작업들은 non-blocking
  • Javascript를 사용한 비동기 통신 방식을 Ajax(Asynchronous Javascript and XML)
  • Http요청(GET, POST), 이벤트 핸들러(click, over …), setTimeout, setInterval

stateful, stateless
컴포넌트를 나누는 또 다른 방식이다.
•stateful 컴포넌트 : 모든 state를 들고있는 컴포넌트
•stateless 컴포넌트: state를 안들고 있고 props 와 같이 받은 데이터만 보여주는 컴포넌트
•리액트는 단방향 통신이다 즉 부모에서 자식으로만 데이터를 전달 할 수 있다.
이를통해 데이터 흐름을 추적하기는 더 쉽지만, 같은 형제끼리 데이터를 주고받기는 힘들다. 그래서 데이터는 주로 부모가 들고있고 자식에게
전달해주는 형식이 된다. state를 들고있는 부모 컴포넌트는 stateful 컴포넌트, 부모가주는 데이터만 받는 컴포넌트를 stateless 컴포넌트라고 한다.
이렇게 컴포넌트를 구성하면 장점은 state가 없는 stateless컴포넌트는 재사용이 쉽고 데이터를 걱정하지 않아도 된다.
•모든 중요한 데이터들은 stateful컴포넌트에 있기 때문에 유지보수가 쉽다 (stateful컴포넌트 하나만 주시하고 관리해주면 되니까)
그래서 최대한 모든 컴포넌트를 stateless로 만들고 몇개의 stateful컴포넌트에서 데이터를 관리하는 구조가 이상적이라고 리액트는 말하고 있다.

import './App.css';
import WeatherBox from './components/WeatherBox';
import WeatherButton from './components/WeatherButton';
import 'bootstrap/dist/css/bootstrap.min.css';
import {Container} from 'react-bootstrap';
import React, {useState, useEffect} from 'react';

const API_KEY = '0d632e0f252fbd9e492d488c78a57484';
const cities = ['paris', 'new York', 'tokyo', 'seoul'];

const App = () => {
  const [city, setCity] = useState(null); //변수, 함수, 초기값주는 것.
  const [weather, setWeather] = useState(null);
  const [loading, setLoading] = useState('');


  const getWeatherByCurrentLocation = async(lat, lon)=>{
    try{
      let url = 
      `https://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=${API_KEY}&units=metric`

      const res = await fetch(url);
      const data = await res.json();
      setWeather(data);
    } catch (err) {
      console(err.message);
    }
  }

  const getCurrentLocation = () => {

    navigator.geolocation.getCurrentPosition((position) => {

      const { latitude, longitude } = position.coords;

      getWeatherByCurrentLocation(latitude, longitude);

      console.log('현재위치?', latitude, longitude);

    });

  };

  const getWeatherByCity = async() =>{
    try{
      let url = 
      `https://api.openweathermap.org/data/2.5/weather?q=${city}&appid=${API_KEY}&units=metric`;

      const res = await fetch(url);
      const data = await res.json();
      setWeather(data);
    }catch(err){
      console.log(err);
    }
  }

  useEffect (() => {
    if(city == null){
      getCurrentLocation();
    } else{
      getWeatherByCity();
    }
  }, [city]);

  const handleCityChange = (city) =>{
    if(city === 'current'){
      setCity(null);
    } else{
      setCity(city);
    }
  };
  return (
    <>
      <Container className="vh-100">
        <div></div>
        <div className='main-container'>
          <WeatherBox weather={weather} />
          <WeatherButton cities={cities}
          handleCityChange={handleCityChange}
          selectedCity={city}
          />
        </div>
      </Container>
    </>
  );
}

export default App;

날씨 api를 이용해서 현재 위치의 날씨를 받아온 코드 이다. 내 현재 위치에 대한 건 아래 사이트를 참조하면 된다.
출처: https://www.w3schools.com/html/html5_geolocation.asp

또한 react-spinner도 사용해보았다. 위치 관련 로딩 문제에 관한 라이브러리.

2. 어려웠던 점 및 해결방안

새로운 라이브러리가 나와서 구글링 해 보았다.
'react-spinner' 란.

API호출시 보통 로딩을 처리하는 동안 Spinner를 표시해서 로딩처리를 사용자에게 알리는 용도로 많이 사용됩니다.

라고 적혀 있었다.
자세한건 아래 페이지에 나와 있다.
출처: https://kimchanjung.github.io/programming/2020/06/26/react-spinner/

3. 학습소감

오늘은 외부 API를 표시해 주는 것 뿐만 아니라, 도시에 따라 다른 날씨와 온도 등이 보여지게 하는데 코드를 작성해 보았다.

profile
친숙한 개발자가 되고픈 사람

0개의 댓글