Skip to content

Commit

Permalink
👔 Update: 맥주 정보 조회 병렬 처리
Browse files Browse the repository at this point in the history
  • Loading branch information
romantech committed Nov 11, 2021
1 parent 5219c99 commit 1adc906
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 8 deletions.
4 changes: 2 additions & 2 deletions src/APIs/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ import axios from 'axios';
const baseUrl = `https://api.punkapi.com/v2`;

export default {
getBeers: () => {
return axios.get(`${baseUrl}/beers?page=1&per_page=80`);
getBeersByPage: (page, num) => {
return axios.get(`${baseUrl}/beers?page=${page}&per_page=${num}`);
},
getSingleBeer: id => {
return axios.get(`${baseUrl}/beers/${id}`);
Expand Down
20 changes: 17 additions & 3 deletions src/Modules/saga/beerListSaga.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { call, put, takeLatest } from 'redux-saga/effects';
import { call, all, put, takeLatest } from 'redux-saga/effects';

import {
GET_BEER_LIST_REQUEST,
Expand All @@ -9,8 +9,22 @@ import APIs from '../../APIs';

function* getBeerList() {
try {
const { data: rawData } = yield call(APIs.getBeers); // yield call은 결과 반환시까지 기다려줌
yield put(getBeerListSuccess(rawData)); // action dispatch
// const { data } = call(APIs.getBeers, 1, 80) -> 결과반환까지 대기
// yield call 첫번째 함수의 파라미터를 넘길 땐 call 두번째 파라미터에 명시
// call(func, funcParams1, funcParams2)

const pageNums = Array.from(Array(5).keys(), x => x + 1); // [1, 2, 3, 4, 5]

// yield all[call(...), call(...)] -> 병렬 처리 promise.all과 동일. 프로미스가 하나라도 거절되면 모두 거절.
const [...dataByPages] = yield all(
pageNums.map(x => call(APIs.getBeersByPage, x, 80)),
); // [{...}, {...}] 페이지별 호출

const mergedPages = dataByPages.reduce(
(merged, { data }) => merged.concat(data),
[],
); // [...]
yield put(getBeerListSuccess(mergedPages)); // action dispatch
} catch (err) {
yield put(getBeerListFailed(err.response.status));
}
Expand Down
7 changes: 4 additions & 3 deletions src/Routes.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { useDispatch, useSelector } from 'react-redux';
import {
BrowserRouter as Router,
Route,
Expand All @@ -15,10 +15,11 @@ import NotFoundPage from './Components/NotFoundPage';

const Routes = function () {
const dispatch = useDispatch();
const { rawData } = useSelector(state => state.beerList);

useEffect(() => {
dispatch(getBeerListRequest());
}, [dispatch]);
if (!rawData || rawData.length < 325) dispatch(getBeerListRequest());
}, [dispatch, rawData]);

return (
<Router>
Expand Down

1 comment on commit 1adc906

@vercel
Copy link

@vercel vercel bot commented on 1adc906 Nov 11, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.