ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 실전프로젝트 4주차 수요일
    카테고리 없음 2022. 1. 12. 20:54

    💡 react-infinite-scroll-component를 사용하기 전에 study

     

    https://www.npmjs.com/package/react-infinite-scroll-component

     

    react-infinite-scroll-component

    An Infinite Scroll component in react.. Latest version: 6.1.0, last published: 10 months ago. Start using react-infinite-scroll-component in your project by running `npm i react-infinite-scroll-component`. There are 244 other projects in the npm registry u

    www.npmjs.com

     
    1.using에서 코드 복사
    <InfiniteScroll
      dataLength={items.length} //This is important field to render the next data
      next={fetchData}
      hasMore={true}
      loader={<h4>Loading...</h4>}
      endMessage={
        <p style={{ textAlign: 'center' }}>
          <b>Yay! You have seen it all</b>
        </p>
      }
      // below props only if you need pull down functionality
      refreshFunction={this.refresh}
      pullDownToRefresh
      pullDownToRefreshThreshold={50}
      pullDownToRefreshContent={
        <h3 style={{ textAlign: 'center' }}>&#8595; Pull down to refresh</h3>
      }
      releaseToRefreshContent={
        <h3 style={{ textAlign: 'center' }}>&#8593; Release to refresh</h3>
      }
    >
      {items}
    </InfiniteScroll>



    2.below~삭제
    <InfiniteScroll
      dataLength={items.length} //This is important field to render the next data
      next={fetchData}
      hasMore={true}
      loader={<h4>Loading...</h4>}
      endMessage={
        <p style={{ textAlign: 'center' }}>
          <b>Yay! You have seen it all</b>
        </p>
      }
     
    >
      {items}
    </InfiniteScroll>

     

    3. const [items,setItems] = useState([])

     

    4. const fetchData = () => {

     

    }

     

    5.useEffect(()=>{
    //데이터 가져오기
    const getComments = async () => {
        const res = await fetch(
           `https:에이피아이주소?page=1&limit=20` //처음20개 데이터 불러오기
    );

     

         const data = await res.json(); //리스폰스를 const data에 저장
         setItems(data)//items는 현재 빈배열. 여기에 처음 20개 데이터를 set해주기
    };
    getCommetList();
    },[])

     

    console.log(items) => 하면 에러나지만 일단 콘솔에 어레이에 들어왓는지 확인



    6.에러잡기
    <InfiniteScroll
      dataLength={items.length} //This is important field to render the next data
      next={fetchData}
      hasMore={true}
      loader={<h4>Loading...</h4>}
      endMessage={
        <p style={{ textAlign: 'center' }}>
          <b>Yay! You have seen it all</b>
        </p>
      }
     
    >
      {items} ////🎈💡👻얘때매 에러
    </InfiniteScroll>

     

    =>
    <InfiniteScroll
      dataLength={items.length} //This is important field to render the next data
      next={fetchData}
      hasMore={true}
      loader={<h4>Loading...</h4>}
      endMessage={
        <p style={{ textAlign: 'center' }}>
          <b>Yay! You have seen it all</b>
        </p>
      }
     
    >
      {items.map((item)=>{
    <div>key={item.id}</div>
    <div>email:{item.email}<div>
    })   ////items가 배열이기 때문에 이런식으로 맵을 돌려서 값을 추출해주기
        =>search_list맵돌리는거랑 똑같
    </InfiniteScroll>



    7.fetch 함수에 consol.log("hello")를 찍어보면
    처음에 20개 배열이 콘솔에 찍히고, 스크롤을 하단으로 내렸을 때
    hello가 찍힌다 => 제일 하단에 도달하면 fetch 가 다음 데이터 불러온다.

     

    8. fetchComments 함수를 만들어준다.
    fetch method를 사용해서 2번째 페이지를 가져올 것
    const fetchComments = aync () => {
      const res = await fetch(
    //page=2로 넣어주기(다음페이지 가져오기)
           `https:에이피아이주소?page=2&limit=20` //처음20개 데이터 불러오기
    );

     

         const data = await res.json(); //리스폰스를 const data에 저장
         return data; //useEffect로 불러온 데이터 형식과 같이 작성해준다
    };
    }



    9. 위에 작성한 함수를 fetchData함수 안에서 실행시켜준다.
    const fetchData = async() =>{
       const commentsFormServer = await fetchComments();
    }
    이제 fetchComments는 스크롤 다운 될 때 불리게됨!
    const fetchData = async() =>{
       const commentsFormServer = await fetchComments();

     

      setItems([...items, ...commentsFormServer])
    //1페이지 데이터인 items와 2페이지 데이터인 commentsFormServer를 결합해서 set해주기
    => items에는 1,2페이지의 데이터가 모두 들어오게 된다.
    }

     

    10. 여기까지하고 콘솔에서 item찍어서 확인해보면
    스크롤 내릴때 40번째까지 데이터가 잘 불려오고
    에러가 찍힘 => 2번째 페이지를 한번 더 불러오고 있다.
    fetchData함수가 2번째 페이지를 다시 불러오고 있음
    데이터 가져오기 호출을 여러 번 방지하기 위해
    두 번째 페이지를 로드한 후 속성을 true에서 false로 업데이트해야 함
    =>새로운 state를 만들자(useState)
    const [hasMore, setHasMore] = useState(true)
    초기값이 true인 hasMore를 hasMore={hasMore}로 주입

     

    11.이제 이 스테이트를 업데이트 해줘야 한다.
    두번째 페이지를 로드하고 항목에서 선택하면 setHasMore(false)로 변경
    const fetchData = async() =>{
       const commentsFormServer = await fetchComments();

     

      setItems([...items, ...commentsFormServer])
      setHasMore(false)
    //호출된 데이터를 다시 가져오는 것을 방지합니다.(중복방지)
    }
    =>에러는 사라지고 스크롤이 끝난 멘트가 보인다!(페이지가 한번만 불려짐)



    12. 40개(2페이지)까지는 가져왓는데 모든 데이터베이스 내용을 가져와야 한다.
    =>다음 페이지를 불러올 새로운 state를 만들어 줘야 한다.
    const [page,setPage]=useState(2)//초기값이 2인 state를 만들어주기
    아까 작성했던 함수에서 page=2가 아니라 page=${page}로 해주기
    초기값이 2이니까 두번째 페이지부터 불러올 것임

     

    const fetchComments = aync () => {
      const res = await fetch(
           `https:에이피아이주소?page=${page}&limit=20`
    );

     

         const data = await res.json();
         return data;
    };
    }

     

    이제 여기서 페이지를 하나씩 증가시켜서 끝까지 불러오면 된다!
    const fetchData = async() =>{
       const commentsFormServer = await fetchComments();

     

      setItems([...items, ...commentsFormServer])
      setHasMore(false)
      setpage(page+1)//여기
    }
    =>여기까지 하면 전과 결과가 같음(아직 page=2까지만 데이터 불러오고 끝남)
    =>setHasMore를 false로 해놨기 때문!
    =>여기에 조건문을 걸어줘야 한다.

     

    const fetchData = async() =>{
       const commentsFormServer = await fetchComments();

     

      setItems([...items, ...commentsFormServer])

     

     if(commentsFormServer.length === 0 || commentsFormServer.length < 20){
       setHasMore(false)
    }
     
      setpage(page+1)//여기
    }
    =>이렇게 하면 마지막 데이터까지 무한스크롤이 잘된다!
    참고↓↓↓
    youtube.com/watch?v=bBUOMy6Tugw
Designed by Tistory.