230717 React로 Netflix 넷플릭스 사이트 만들기

Yujung Kim·2023년 7월 17일
0

React

목록 보기
14/17

텍스트> 오늘 알고갈 것들..

  • useDispatch() & useSelector()
  • api 및 axios 사용법

References:
https://velog.io/@miso1489/series/%EB%84%B7%ED%94%8C%EB%A6%AD%EC%8A%A4-%ED%81%B4%EB%A1%A0%EC%BD%94%EB%94%A9
https://velog.io/@smooth97/Netflix-Clone-1-API-

Root Folder:
YJ\YJ-github\GMA\YJ-React\230717\netflix

시작 전 설치할 것들

npm install react-bootstrap bootstrap
npm install react-router-dom
npm install redux react-redux
npm install redux-thunk
npm install --save-dev redux-devtools-extension

🍿 Redux - thunk & devtools

Thunk

리덕스 앱에서 '사이드 이펙트'를 특별한 방법으로 처리하기 위한 Redux 미들웨어로,

만약 리듀서가 사이드 이펙트를 갖고 있으면 아래와 같은 에러가 발생하는데,
Error: Actions must be plain objects. Use custom middleware for async actions.
redux-thunk를 사용하면 이러한 문제를 해결할 수 있다.

❔ 리듀서의 side-effects

6.1. What are side effects?

Redux handles data with as much purity as possible, but for most applications you can’t avoid side effects. Side effects are required to interact with the world outside of your client application. Side effects, in this context, are any interactions with the world beyond your Redux application. Most examples can be summarized as interactions with a server or local storage. For example, you might store an authorization token in a browser’s sessionStorage, fetching data from a remote server, or recording an analytics event.

Devtools

리덕스 개발자 도구를 사용하면 현재 스토어의 상태를 개발자 도구에서 조회 할 수 있고 지금까지 어떤 액션들이 디스패치 되었고, 액션에 따라 변화한 상태를 확인 할 수 있어 리덕스를 상태를 쉽게 알 수있고 크롬 웹 스토어 에서 설치 후 사용한다.

🍿 AXIOS

: Axios는 Promise 기반의 async/await 문법을 사용하여 XHR요청을 매우 쉽게 할 수 있어
HTTP통신을 하는데 매우 인기있는 Javascript 라이브러리
(*API 호출 시, 루트 URL이 공통인 경우, 경로를 반복해서 작성하지 않고 사용 가능하게 함)

참고링크:
https://github.com/axios/axios

1. axios 설치

npm install axios

2. redux 폴더 안 api.js 생성

import axios from "axios";

//
import axios from "axios";

// 1. instance 객체 생성
const api = axios.create({
  baseURL: "https://api.themoviedb.org/3",
  headers: { "Content-Type": "application/json" },
});

// 2. interceptor
// Add a request interceptor
api.interceptors.request.use(
  function (config) {
    // Do something before request is sent
    console.log("request start", config);
    return config;
  },
  function (error) {
    // Do something with request error
    console.log("request error", error);
    return Promise.reject(error);
  }
);

// Add a response interceptor
api.interceptors.response.use(
  function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // Do something with response data
    console.log("request response", response);
    return response;
  },
  function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    console.log("request error", error);
    return Promise.reject(error);
  }
);

export default api;

3. reducer 정의

redux\reducers\movieReducer.js

let initialState = {
  popularMovies: {},
  topRatedMovies: {},
  upComingMovies: {},
};

function movieReducer(state = initialState, action) {
  let { type, payload } = action;
  switch (type) {
    case "GET_MOVIES_SUCCESS":
      return {
        ...state,
        popularMovies: payload.popularMovies,
        topRatedMovies: payload.topRatedMovies,
        upComingMovies: payload.upComingMovies,
      };
    default:
      return { ...state };
  }
}

export default movieReducer;

3. action 정의

redux\actions\movieAction.js

import api from "../api";

const API_KEY = process.env.REACT_APP_API_KEY;

function getMovies() {
  return async (dispatch) => {
    const popularMovieApi = api.get(
      `movie/popular?api_key=${API_KEY}&language=en-US&page=1`
    );
    const topRatedApi = api.get(
      `movie/top_rated?api_key=${API_KEY}&language=en-US&page=1`
    );
    const upComingApi = api.get(
      `movie/upcoming?api_key=${API_KEY}&language=en-US&page=1`
    );

    let [popularMovies, topRatedMovies, upComingMovies] = await Promise.all([
      popularMovieApi,
      topRatedApi,
      upComingApi,
    ]);
    dispatch({
      type: "GET_MOVIES_SUCCESS",
      payload: {
        popularMovies: popularMovies.data,
        topRatedMovies: topRatedMovies.data,
        upComingMoviesMovies: upComingMovies.data,
      },
    });
  };
}

export const movieAction = {
  getMovies,
};

💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨

API_KEY를 직접 기재할 시 개인정보 유출 우려!! 따라서 아래 과정 추가됨

  1. 루트폴더에 .env 파일 생성 후 추가
REACT_APP_API_KEY=b63dfb72034b5ca111956fae9f1a2a66s
  1. .gitingnore 에 .env 추가 (github에 업로드 시 해당 파일은 업로드되지 않음)
  2. movieAction.js에 추가
const API_KEY = process.env.REACT_APP_API_KEY;

💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨💨

🎠 슬라이더 플러그인

https://www.npmjs.com/package/react-multi-carousel

0개의 댓글

관련 채용 정보