section3 cmarket-redux

유희준·2023년 4월 25일
0

section3

목록 보기
4/5
post-custom-banner

index.js

export const ADD_TO_CART = 'ADD_TO_CART' // 문자는 재사용과 오타가능성이 있어 const로 저장
export const REMOVE_FROM_CART = "REMOVE_FROM_CART";
export const SET_QUANTITY = "SET_QUANTITY";
export const NOTIFY = "NOTIFY";
export const ENQUEUE_NOTIFICATION = "ENQUEUE_NOTIFICATION";
export const DEQUEUE_NOTIFICATION = "DEQUEUE_NOTIFICATION";

// actions creator functions (액션생성자)
export const addToCart = (itemId) => { //추가시 수량과 id필요
  return {
    type: ADD_TO_CART,
    payload: {
      quantity: 1,
      itemId
    }
  }
}

export const removeFromCart = (itemId) => { //삭제시 아이디만 필요
  return {
    type: REMOVE_FROM_CART,
    payload: {
      itemId
    }
  }
}

export const setQuantity = (itemId, quantity) => {//수량체크시 id, 수량 모두 필요
  return {
    type: SET_QUANTITY,
    payload: {
      itemId,
      quantity
    }
  }
}

export const notify = (message, dismissTime = 5000) => dispatch => {
  const uuid = Math.random()
  dispatch(enqueueNotification(message, dismissTime, uuid))
  setTimeout(() => {
    dispatch(dequeueNotification())
  }, dismissTime)
}

export const enqueueNotification = (message, dismissTime, uuid) => {
  return {
    type: ENQUEUE_NOTIFICATION,
    payload: {
      message,
      dismissTime,
      uuid
    }
  }
}

export const dequeueNotification = () => {
  return {
    type: DEQUEUE_NOTIFICATION
  }
}

itemReducer.js

import { REMOVE_FROM_CART, ADD_TO_CART, SET_QUANTITY } from "../actions/index";
import { initialState } from "./initialState";

const itemReducer = (state = initialState, action) => {

  switch (action.type) {
    case ADD_TO_CART:
      return {...state, cartItems: [...state.cartItems, action.payload]} //cartItems에 추가 액션값 
    case REMOVE_FROM_CART:
      return {...state, cartItems: state.cartItems.filter(el => el.itemId !== action.payload.itemId)} // 요소 중 같은것은 뺌
    case SET_QUANTITY: //상품수량 조절
      let targetIdx = state.cartItems.findIndex(el => el.itemId === action.payload.itemId) 
      return {...state, cartItems: state.cartItems.map((el, idx) => idx === targetIdx ? action.payload : el )}
    default:
      return state;
  }
}

export default itemReducer;

dispetch 사용

 const state = useSelector(state => state.itemReducer);
  const { cartItems, items } = state
  const dispatch = useDispatch();

 const handleQuantityChange = (quantity, itemId) => {
    //TODO: dispatch 함수를 호출하여 액션을 전달하세요.
    dispatch(setQuantity(itemId,quantity))
  }
 
   const handleDelete = (itemId) => {
    setCheckedItems(checkedItems.filter((el) => el !== itemId))
    dispatch(removeFromCart(itemId))
    //TODO: dispatch 함수를 호출하여 액션을 전달하세요.
  }
profile
매일 뭐든하기
post-custom-banner

0개의 댓글