Redux Toolkit

이시원·2022년 9월 15일
0

Redux 공부

목록 보기
12/12
post-thumbnail

Redux Toolkit


  • 설치

npm install @reduxjs/toolkit

기존의 redux는 uninstall 해도 된다.


  • 세팅

1. action

기존

function getProducts(searchQuery) {
  return async (dispatch, getState) => {
    let url = `https://my-json-server.typicode.com/mynameisleesiwon/hnm-react-router-practice/products?q=${searchQuery}`;
    let response = await fetch(url);
    let data = await response.json();
    dispatch({ type: "GET_PRODUCT_SUCCESS", payload: { data } });
  };
}

function getProductDetail(id) {
  return async (dispatch, getState) => {
    let url = `https://my-json-server.typicode.com/mynameisleesiwon/hnm-react-router-practice/products/${id}`;
    let response = await fetch(url);
    let data = await response.json();

    dispatch({ type: "GET_PRODUCT_DETAIL", payload: { data } });
  };
}

export const productAction = { getProducts, getProductDetail };

toolkit

import { productActions } from "../reducers/productReducer";

function getProducts(searchQuery) {
  return async (dispatch, getState) => {
    let url = `https://my-json-server.typicode.com/mynameisleesiwon/hnm-react-router-practice/products?q=${searchQuery}`;
    let response = await fetch(url);
    let data = await response.json();
    // 매개변수로 전달된 값은 알아서 payload라는 필드 아래로 들어감
    dispatch(productActions.getAllProducts({ data }));
  };
}

function getProductDetail(id) {
  return async (dispatch, getState) => {
    let url = `https://my-json-server.typicode.com/mynameisleesiwon/hnm-react-router-practice/products/${id}`;
    let response = await fetch(url);
    let data = await response.json();
    dispatch(productActions.getProductDetail({ data }));
  };
}

export const productAction = { getProducts, getProductDetail };

2. reducer

기존

let initialState = {
  productList: [],
  product: null,
};

function productReducer(state = initialState, action) {
  let { type, payload } = action;
  switch (type) {
    case "GET_PRODUCT_SUCCESS":
      return { ...state, productList: payload.data };
    case "GET_PRODUCT_DETAIL":
      return { ...state, product: payload.data };
    default:
      return { ...state };
  }
}

export default productReducer;

toolkit

createSlice : 반드시 3개의 매개변수를 가진다.

  • name : slice의 이름
  • initialState : 초기값
  • reducers : 객체(함수로 이루어진)
    • 함수는 state와 action을 매개변수로 받는다.
import { createSlice } from "@reduxjs/toolkit";

let initialState = {
  productList: [],
  product: null,
};

const productSlice = createSlice({
  name: "product",
  initialState,
  reducers: {
    getAllProducts(state, action) {
      // return과 ...state 할 필요없다.
      state.productList = action.payload.data;
    },
    getProductDetail(state, action) {
      state.product = action.payload.data;
    },
  },
});

console.log("productSlice",productSlice);

// productSlice안에 있는 reducer, actions를 전달
export const productActions = productSlice.actions;
export default productSlice.reducer;


3. store

기존

// store.js
import { createStore, applyMiddleware } from "redux";
import { composeWithDevTools } from "redux-devtools-extension";
import thunk from "redux-thunk";
import rootReducer from "./reducers";

let store = createStore(
  rootReducer,
  composeWithDevTools(applyMiddleware(thunk))
);

export default store;
// index.js
import { combineReducers } from "redux";
import authentiateReducer from "./authentiateReducer";
import productReducer from "./productReducer";

export default combineReducers({
  auth: authentiateReducer,
  product: productReducer,
});

toolkit

// store.js
import { configureStore } from "@reduxjs/toolkit";
import productReducer from "./reducers/productReducer";
import authentiateReducer from "./reducers/authentiateReducer";

let store = configureStore({
  reducer: {
    auth: authentiateReducer,
    product: productReducer,
  },
});

export default store;
  • configureStore에 자동으로 셋업되어 있는 것들
    • composeWithDevTools
    • applyMiddleware(thunk)
    • combinereducer
      - index.js 필요없음

profile
코딩공부

0개의 댓글