components/NewsList.js

    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 NewsList = () => {
      const [articles, setArticles] = useState(null);
      const [loading, setLoading] = useState(false);
     
      useEffect(() => {
        // async 사용하는 함수 따로 선언
        const fetchData = async () => {
          setLoading(true);
          try {
            const response = await axios.get(
              'https://newsapi.org/v2/top-headlines?country=kr&apiKey=0a8c4202385d4ec1bb93b7e277b3c51f',
            );
            setArticles(response.data.articles);
          } catch (e) {
            console.log(e);
          }
          setLoading(false);
        };
        fetchData();
      }, []);
     
      // 대기 중일 
      if (loading) {
        return <NewsListBlock>대기 ...</NewsListBlock>;
      }
      // 아직 articles 값이 설정되지 않았을 
      if (!articles) {
        return null;
      }
     
      // articles 값이 유효할 
      return (
        <NewsListBlock>
          {articles.map(article => (
            <NewsItem key={article.url} article={article} />
          ))}
        </NewsListBlock>
      );
    };
     
    export default NewsList;

    신간 소식 구독하기
    뉴스레터에 가입하시고 이메일로 신간 소식을 받아 보세요.