PaulMuadDibUsul / react-group-study

0 stars 5 forks source link

14 스터디 퀴즈 [외부 API를 연동하여 뉴스 뷰어 만들기] #45

Open EYEG opened 4 months ago

EYEG commented 4 months ago
import React, { useState, useEffect } from 'react';
import styled from 'styled-components';
import NewsItem from './NewsItem';
import axios from 'axios';

const NewsListBlock = styled.div`
  box-sizing: border-box;
  padding-bottom: 3rem;
  width: 768px;
  margin: 0 auto;
  margin-top: 2rem;
  @media screen and (max-width: 768px) {
    width: 100%;
    padding-left: 1rem;
    padding-right: 1rem;
  }
`;

const NewsListAxios = ({ category }) => {
  const [articles, setArticles] = useState(null);
  const [loading, setLoading] = useState(false);

  useEffect(() => {
    const fetchData = async () => {
      setLoading(true);
      try {
        const query = category === 'all' ? '' : `&category=${category}`;
        const response = await axios.get(
          `https://newsapi.org/v2/top-headlines?country=kr${query}&apiKey=0a8c4202385d4ec1bb93b7e277b3c51f`
        );
        setArticles(response.data.articles);
      } catch (e) {
        console.log(e);
      }
      setLoading(false);
    };
    fetchData();
  }, [category]);

  if (loading) {
    return <NewsListBlock>대기 중...</NewsListBlock>;
  }
  if (!articles) {
    return null;
  }

  return (
    <NewsListBlock>
      {articles.map((article) => (
        <NewsItem key={article.url} article={article} />
      ))}
    </NewsListBlock>
  );
};

export default NewsListAxios;

보다 효율적인 렌더링을 위해 수정되면 더 좋을 것 같은 부분들을 자유롭게 말해보기 (그룹 스터디에서 같이 공부했던 사항들과 혹은 각자 알고 있었던 사항들 포함)

ohr0226 commented 4 months ago

useEffect에 등록한 함수는 async 키워드를 붙이면 안되는데, 그 이유가 뭘까욥

정답
useEffect에는 정리(cleanup)하는 기능이 있는데, 함수에서 Promise를 반환하면 이 기능과 충돌이 생기기 때문이다.
seokhj commented 4 months ago

다음 중, API가 작동하는 방식 중 틀린 것 1개는 무엇일까요?

  1. SOAP API
  2. Rapid API
  3. RPC API
  4. REST API
  5. Websocket API
정답 및 참고

2. Rapid API

amazon API 정의
REST와 Websocket API에 대하여
ohr0226 commented 4 months ago

아래 코드를 구현했을 때 나오는 콘솔의 결과를 나열해보세용

console.log('시작')

setTimeout(function(){
    console.log('중간')
},0);

Promise.resolve()
    .then(function (){
            console.log('프로미스')
        }
    );

console.log('끝')
정답
시작 끝 중간 프로미스



.... 일줄 알았죠?
프로미스는 콜백큐에서 우선순위가 높아서 먼저 실행이 됩니당
결론은 **시작 끝 프로미스 중간** 순서로 출력이 됩니다


그리고 여기서 중요한 사실은 promise는 동기입니다 다만 then이 있으면 비동기로 실행이된대요 ㅎㄷㄷ
cheesepizza453 commented 4 months ago

아래 코드에서 콜백함수와 고차함수에 해당하는 부분을 각각 말해주세용!!

function repeat (n, f) {
    for (var i=0; i< n; i++) {
        f(i);
    }
}

const logAll = function (i) {
    console.log(i)
};

repeat(5, logAll);

var logOdds = function (i) {
    if (i % 2) console.log(i)
}

repeat(5, logOdds);
andrewylies commented 4 months ago

Q. Promise.all을 사용하면 안되는 경우는 언제인가요?