OP.GG 클론하기 - 롤 전적 검색 사이트 만들기 11

2020. 10. 20. 19:29클론을 해보자

이번 글에서는 redux라는 것을 사용하여 프론트엔드 작업을 이어서 해보도록 하겠습니다.

redux는 django의 view.py에서 정의했던 api들을 연결해주는 과정이라고 생각하시면 됩니다.

 

src아래에 redux 폴더를 만들어줍니다. redux 폴더 아래에 configureStore.js 파일을 만들고, modules 폴더를 만들어줍니다. 또한 modules 폴더 아래에는 lol.js를 만들어줍니다. 구성을 그림으로 보면 다음과 같습니다.

 

redux 구성

configureStore.js와 lol.js를 채워보도록 하겠습니다. 

configureStore.js를 다음과 같이 작성합니다.

#configureStore.js

import { combineReducers, createStore, applyMiddleware } from "redux";
import {routerMiddleware } from 'connected-react-router'
import { composeWithDevTools } from "redux-devtools-extension";
import { connectRouter } from 'connected-react-router'
import createHistory from "history/createBrowserHistory";
import thunk from "redux-thunk";
import lol from "redux/modules/lol";

const env = process.env.NODE_ENV;

const history = createHistory();

const middlewares = [thunk, routerMiddleware(history)];

console.log(history)
if (env === "development") {
  const { logger } = require("redux-logger");
  middlewares.push(logger);
}

const reducer = combineReducers({
    lol,
  router: connectRouter(history)
});

let store;

if (env === "development") {
  store = initialState =>
    createStore(reducer, composeWithDevTools(applyMiddleware(...middlewares)));
} else {
  store = initialState => createStore(reducer, applyMiddleware(...middlewares));
}

export { history };

export default store();

redux는 api를 request하고 response된 결과를 객체로 넘겨주는 중간자 역할을 수행합니다. lol.js를 작성해보도록 하겠습니다. 첫 번째 api인 getTier API 부터 작성해보겠습니다.

const SET_TIER = "SET_TIER";


function setTier(Tier) {
  return {
    type: SET_TIER,
    Tier
  };
}

SET_TIER라는 타입을 정해주고 setTier function을 만들어줍니다. 그 다음 api를 request하는 getTier funtion을 만들어줍니다.

function getTier(summoner_name) {
  return (dispatch, getState) => {
    fetch("/lol/tier/?summoner_name="+summoner_name, {
    })
      .then(response => {
        return response.json();
      })
      .then(json => {
        dispatch(setTier(json));
      });
  };
}

그 다음 reducer를 통해, action.type에 따라 SET을 해주는 함수를 작성합니다.

const initialState = {};



function reducer(state = initialState, action) {
  switch (action.type) {
    case SET_TIER:
      return applySetTier(state, action);
    default:
      return state;
  }
}



function applySetTier(state, action) {
  const { Tier } = action;
  return {
    ...state,
    Tier
  };
}
const actionCreators = {
  getTier,
};

export { actionCreators };


export default reducer;

여기까지하면 lol.js가 사용가능합니다. 물론 아직 두개의 api에 대해 더 작성해야 합니다. 남은 두가지 api에 대해서 작성해보도록 하겠습니다.

#lol.js
const SET_TIER = "SET_TIER";
const SET_RATE = "SET_RATE";
const SET_INGAME = "SET_INGAME";
function setTier(Tier) {
  return {
    type: SET_TIER,
    Tier
  };
}
function setRate(Rate) {
  return {
    type: SET_RATE,
    Rate
  };
}
function setIngame(Ingame) {
  return {
    type: SET_INGAME,
    Ingame
  };
}
function getTier(summoner_name) {
  return (dispatch, getState) => {
    fetch("/lol/tier/?summoner_name="+summoner_name, {
    })
      .then(response => {
        return response.json();
      })
      .then(json => {
        dispatch(setTier(json));
      });
  };
}
function getRate(summoner_name) {
  return (dispatch, getState) => {
    fetch("/lol/rate/?summoner_name="+summoner_name, {
    })
      .then(response => {
        return response.json();
      })
      .then(json => {
        dispatch(setRate(json));
      });
  };
}
function getIngame(summoner_name) {
  return (dispatch, getState) => {
    fetch("/lol/ingame/?summoner_name="+summoner_name, {
    })
      .then(response => {
        return response.json();
      })
      .then(json => {
        dispatch(setIngame(json));
      });
  };
}

const initialState = {};

function reducer(state = initialState, action) {
  switch (action.type) {
    case SET_TIER:
      return applySetTier(state, action);
    case SET_RATE:
      return applySetRate(state, action);
    case SET_INGAME:
      return applySetIngame(state, action);
    default:
      return state;
  }
}



function applySetTier(state, action) {
  const { Tier } = action;
  return {
    ...state,
    Tier
  };
}

function applySetRate(state, action) {
  const { Rate } = action;
  return {
    ...state,
    Rate
  };
}

function applySetIngame(state, action) {
  const { Ingame } = action;
  return {
    ...state,
    Ingame
  };
}
const actionCreators = {
  getTier,
  getRate,
  getIngame,
};

export { actionCreators };


export default reducer;

이상 완성된 lol.js입니다. 여기까지 하면 우리가 만들 simple.gg의 redux를 완성한 것입니다.