๐Ÿคฒ React ํด๋ง(Polling) ํ•˜๋Š” ๋ฐฉ๋ฒ•

leehyunjuยท2023๋…„ 1์›” 21์ผ
1
post-thumbnail
post-custom-banner

๐Ÿ“ Polling์ด๋ž€ ?

  • ํด๋ผ์ด์–ธํŠธ ์ชฝ์—์„œ n์ดˆ ๊ฐ„๊ฒฉ์œผ๋กœ ๊ณ„์†ํ•ด์„œ HTTP ์š”์ฒญ์„ ๋ณด๋‚ด๋Š” ๊ฒƒ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.

๐Ÿ”ธ ์žฅ์ 

  • ๊ตฌํ˜„์ด ์‰ฝ์Šต๋‹ˆ๋‹ค.

๐Ÿ”ธ ๋‹จ์ 

  • HTTP๋Š” ๋‹จ๋ฐ˜ํ–ฅ ํ†ต์‹ ์ด๋ผ ์ด ํ”„๋กœํ† ์ฝœ์ด ๊ณ„์†ํ•ด์„œ ์š”์ฒญ์„ ๋‚ ๋ฆฌ๋ฉด ์„œ๋ฒ„์˜ ๋ถ€๋‹ด์ด ์ฆ๊ฐ€ํ•˜๊ฒŒ ๋ฉ๋‹ˆ๋‹ค.

๐Ÿ”ธ ์‚ฌ์šฉ๋ฒ•

  • Polling์„ ์ž‘์—…์„ ์œ„ํ•ด setInterval์„ ์‚ฌ์šฉํ•˜์—ฌ ๋ฐ์ดํ„ฐ ์š”์ฒญ์„ ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
// API ๋ฐ์ดํ„ฐ ํ˜ธ์ถœ ํ•จ์ˆ˜
const dataApi = async () => {
  const rankApi = await fetcher(METHOD.GET, `/domestic/rank`);
        setRankList(rankApi.data);
};

 useEffect(() => {
        let polling = setInterval(() => {
            dataApi();
        }, 60000);

        // ํŽ˜์ด์ง€์— ๋ฒ—์–ด๋‚  ๊ฒฝ์šฐ polling X
        return () => {
            clearInterval(polling);
        };
    }, []);

์ด๋Ÿฐ์‹์œผ๋กœ setInterval ์„ ์‚ฌ์šฉํ•˜์—ฌ ์ฃผ๊ธฐ ์‹œ๊ฐ„์„ ๋„ฃ๊ณ  (60000 = 1๋ถ„) 1๋ถ„์— ํ•œ ๋ฒˆ์”ฉ API๋ฅผ ์ƒˆ๋กญ๊ฒŒ call ์‹œํ‚ด์œผ๋กœ์จ ์‹ค์‹œ๊ฐ„์œผ๋กœ ๋ณ€๋™๋˜๋Š” ๋ฐ์ดํ„ฐ๋ฅผ ํ™”๋ฉด์—์„œ ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

useEffect๋ฅผ ์‚ฌ์šฉํ•ด์„œ ํŽ˜์ด์ง€๊ฐ€ ๋ฒ—์–ด๋‚  ๋•Œ willdidMount ์™€ ๊ฐ™์€ ์—ญํ• ์ธ useEffect์˜ return ๋ฌธ ์•ˆ์— clearInterval์„ ํ•ด์ค๋‹ˆ๋‹ค.


๋˜ ๋‹ค๋ฅธ ๋ฐฉ์‹์œผ๋กœ๋Š” ์›น์†Œ์ผ“์„ ์‚ฌ์šฉํ•ด ๋ณผ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค. ์›น์†Œ์ผ“์€ ํด๋ผ์ด์–ธํŠธ์™€ ์„œ๋ฒ„ ์‚ฌ์ด์˜ ์–‘๋ฐฉํ–ฅ ํ†ต์‹ ์„ ์˜๋ฏธํ•ฉ๋‹ˆ๋‹ค.

profile
์•„๋Š‘ํ•œ ๋‡Œ๊ณต๊ฐ„ ๐Ÿง 
post-custom-banner

0๊ฐœ์˜ ๋Œ“๊ธ€