reducer 만들기

이시원·2022년 9월 16일
0
post-thumbnail
  • action

// movieAction.js
import api from "../api";
import { movieActions } from "../reducers/movieReducer";

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(
      movieActions.getMovies({
        popularMovies: popularMovies.data,
        topRatedMovies: topRatedMovies.data,
        upComingMovies: upComingMovies.data,
      })
    );
    console.log(popularMovies);
    console.log(topRatedMovies);
    console.log(upComingMovies);
  };
}

export const movieAction = { getMovies };

  • reducer

// movieReducer.js
import { createSlice } from "@reduxjs/toolkit";

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

const movieSlice = createSlice({
  name: "movie",
  initialState,
  reducers: {
    getMovies(state, action) {
      state.popularMovies = action.payload.popularMovies;
      state.topRatedMovies = action.payload.topRatedMovies;
      state.upComingMovies = action.payload.upComingMovies;
    },
  },
});

export const movieActions = movieSlice.actions;
export default movieSlice.reducer;

  • store

import { configureStore } from "@reduxjs/toolkit";
import movieReducer from "./reducers/movieReducer";

let store = configureStore({
  reducer: {
    movie: movieReducer,
  },
});

export default store;

profile
코딩공부

0개의 댓글