Framework/React

[React] ๊ธฐ์กด ๋ฐ์ดํ„ฐ์—์„œ API Fetching ํ›„(๋”๋ณด๊ธฐ ๋ฒ„ํŠผ ํด๋ฆญ ํ›„) ์ƒˆ๋กœ ๋ถˆ๋Ÿฌ์˜จ ๋ฐ์ดํ„ฐ ํ•ฉ์น˜๋Š” ๋ฐฉ๋ฒ• / ๋”๋ณด๊ธฐ ๋ฒ„ํŠผ ํŽ˜์ด์ง€๋„ค์ด์…˜

yuri lee 2023. 2. 11. 20:11
๋ฐ˜์‘ํ˜•

 

Intro 

์•ˆ๋…•ํ•˜์„ธ์š”. ์ด๋ฒˆ ์‹œ๊ฐ„์—๋Š” React์—์„œ  ๊ธฐ์กด ๋ฐ์ดํ„ฐ์—์„œ ๋”๋ณด๊ธฐ ๋ฒ„ํŠผ ํด๋ฆญ ํ›„ ์ƒˆ๋กœ ๋ถˆ๋Ÿฌ์˜จ ๋ฐ์ดํ„ฐ ํ•ฉ์น˜๋Š” ๋ฐฉ๋ฒ•์— ๋Œ€ํ•ด ์•Œ์•„๋ณด๊ฒ ์Šต๋‹ˆ๋‹ค. 

 

๊ณต์ง€์‚ฌํ•ญ ๋ชฉ๋ก ์กฐํšŒ ๊ธฐ๋Šฅ์„ ๊ตฌํ˜„ํ•˜๋˜ ๋„์ค‘ ๋ฆฌ์ŠคํŠธ๊ฐ€ ๋งŽ์•„์งˆ ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์•„ ๋”๋ณด๊ธฐ ๋ฒ„ํŠผ UI๋ฅผ ์ถ”๊ฐ€ํ•˜๊ธฐ๋กœ ๊ฒฐ์ •ํ–ˆ์Šต๋‹ˆ๋‹ค. ์ฐธ๊ณ ๋กœ API๋Š” ์Šคํ”„๋ง๋ถ€ํŠธ์˜ Pageable ๋ฅผ ์‚ฌ์šฉํ–ˆ์Šต๋‹ˆ๋‹ค. ์ฆ‰ ๊ธฐ์กด ๋ฐ์ดํ„ฐ์—์„œ  ๋”๋ณด๊ธฐ ๋ฒ„ํŠผ UI๋ฅผ ํด๋ฆญํ•  ๋•Œ๋งˆ๋‹ค page ๊ฐ€ +1 ์”ฉ ์ฆ๊ฐ€ํ•˜๋ฉด์„œ ์ƒˆ๋กœ ๋ถˆ๋Ÿฌ์˜จ ๋ฐ์ดํ„ฐ๋ฅผ ํ™”๋ฉด์— ๋ณด์—ฌ์ค˜์•ผ ํ–ˆ์Šต๋‹ˆ๋‹ค. 

 

How to implement

์•„๋ž˜์™€ ๊ฐ™์ด NoticeList ์ปดํฌ๋„ŒํŠธ๊ฐ€ ์žˆ๋‹ค๊ณ  ๊ฐ€์ •ํ•ด๋ด…์‹œ๋‹ค. fetchNotice๋ผ๋Š” ํ•จ์ˆ˜๋ฅผ ๋ถˆ๋Ÿฌ์˜ฌ ๋•Œ๋งˆ๋‹ค, ๊ธฐ์กด ๋ฐ์ดํ„ฐ์— ์ƒˆ๋กœ ๋ถˆ๋ ค์ง„ ๋ฐ์ดํ„ฐ๋ฅผ ์ถ”๊ฐ€ํ•ด์ค˜์•ผ ํ•ฉ๋‹ˆ๋‹ค. ํ•˜์ง€๋งŒ ์œ„ ์ฝ”๋“œ์—์„œ๋Š” ์ƒˆ๋กœ ๋ถˆ๋ ค์ง„ ๋ฐ์ดํ„ฐ๋งŒ์„ setNoticeList๋ฅผ ํ†ตํ•ด ์ €์žฅํ•ด์ฃผ๊ณ  ์žˆ์Šต๋‹ˆ๋‹ค. 

function NoticeList() {
  const [noticeList, setNoticeList] = useState([]);

  const request = `https://api/v1/notices`;

  const fetchNotice = async () => {
    try {
      const response = await axios.get(request);
      const responseResult = response.data;
      setNoticeList(responseResult.items);
    } catch (error) {
      console.log(error.message);
    }
  };

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

  return (
    <>
      <div className="m-8">
        <NoticeCard notices={noticeList} />
        <button
          onClick={fetchNotice()}
        >
          ๋”๋ณด๊ธฐ
        </button>
      </div>
    </>
  );
}

export default NoticeList;

 

์ด ๋™์ž‘์€ ์ €ํฌ๊ฐ€ ์›ํ•˜๋Š” ๊ฒŒ ์•„๋‹™๋‹ˆ๋‹ค. ๊ธฐ์กด ๋ฐ์ดํ„ฐ์— ์ƒˆ๋กœ ๋ถˆ๋ ค์ง„ ๋ฐ์ดํ„ฐ๋ฅผ ์ถ”๊ฐ€ํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” setNoticeList (responseResult.items); ๋Œ€์‹ ์— ์•„๋ž˜์˜ ์ฝ”๋“œ๋ฅผ ํ™œ์šฉํ•˜์‹œ๋ฉด ๋ฉ๋‹ˆ๋‹ค. 

setvideoList((oldData) => [...oldData, ...responseResult.items]);

 

Using the State Hook

state hook์„ ํ™œ์šฉํ•œ ์˜ˆ์ œ๋ผ๊ณ  ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. 

const [state, setState] = useState({});
setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

https://stackoverflow.com/questions/73526551/how-to-load-more-data-as-a-result-of-button-click-for-data-fetching-that-require

https://reactjs.org/docs/hooks-reference.html#usestate:%7E:text=be%20skipped%20completely.-,Note,more%20suited%20for%20managing%20state%20objects%20that%20contain%20multiple%20sub%2Dvalues.,-Lazy%20initial%20state

๋ฐ˜์‘ํ˜•