59일차

그루트·2021년 11월 13일
0
post-custom-banner

import React, { useState, useEffect } from "react";
import styled from "styled-components";

import { apis } from "../shared/axios";

import { ImSearch } from "react-icons/im";
import { RiArrowUpSLine } from "react-icons/ri";

import MemberListCard from "../components/MemberListCard";

const MemberList = (props) => {
const [searchTerm, setSearchTerm] = useState("");

//무한스크롤
const [page, setPage] = useState(1);
const [next, setNext] = useState(true);
const [fetching, setFetching] = useState(false);

const [alluser, setAllUser] = useState([]);
const getMemberDate = async () => {
setFetching(true);
setPage(page + 1);
if (!next) {
return;
}
const data = await apis.getMemberList(page);
const allusers = data.data.user;
console.log(allusers);
setAllUser([...alluser, ...allusers]);
if (allusers.length < 11) {
setNext(false);
}
setFetching(false);
};

useEffect(() => {
getMemberDate();
}, []);

const handleScroll = () => {
const scrollHeight = document.documentElement.scrollHeight;
const scrollTop = document.documentElement.scrollTop;
const clientHeight = document.documentElement.clientHeight;

if (scrollTop + clientHeight >= scrollHeight && !fetching) {
  getMemberDate();
}

};

useEffect(() => {
window.addEventListener("scroll", handleScroll);
return () => {
window.removeEventListener("scroll", handleScroll);
};
});

return (
<>


<SearchInput
placeholder="멤버 검색"
type="text"
onClick={(e) => {
setSearchTerm(e.target.value);
}}
/>


{alluser.map((user, idx) => {
return <MemberListCard {...user} key={idx} />;
})}

<UpScroll
onClick={() => {
window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
}}

  >
    <RiArrowUpSLine />
  </UpScroll>
</>

);
};

무한 스크롤을 적용해보았다.
전에 observer 기능을 썼는데 쉽다면 쉽겠지만
개인적으로 조금 어려웠으므로 고전적인 방법을 공부하고 적용했다.

profile
i'm groot
post-custom-banner

0개의 댓글