ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • OnlineShop 만들기 - 12) Cart Page 만들기 3 (cart remove Function 만들기)
    NODE.JS 2021. 5. 16. 17:34

     

    이번에는 카트에서 상품을 삭제하는 기능을 구현한다.

     

    삭제 함수는 cartpage에 구현하되

     삭제 버튼은 userCardBlock에 있으므로 함수를 prop으로 전달해준다. 

        //카트에서 상품 삭제
        const removeFromCart = (productId) => {
        }
        
        
                    <UserCardBlock
                        products={props.user.cartDetail}
                        removeItem={removeFromCart}
                    />
    

     

    userCardBlock에서 아이템정보를 렌더링 할 때 remove 버튼을 누르면 이 함수가 작동하도록 작성 해주자. 

        const renderItems = () => (//아이템들을 화면에 나타나도록 하자. 
    
                    <td><button 
                    onClick={()=> props.removeItem(product._id)}
                    >Remove </button> </td>
                </tr>
            ))
        )

     

    cartPage에서 함수를 작성한다. 

        import {getCartItems, removeCartItem} from '../../../_actions/user_actions'//redux를 이용하니 actions에서 가져와서 실행한다. 
    
        //카트에서 상품 삭제
        const removeFromCart = (productId) => {//삭제할 상품아이디를 받는다. 
            //리덕스를 이용한다. ->actions를 작성해줘야한다. 
            dispatch(removeCartItem(productId))
                .then((response) => {
                    if (response.payload.cartDetail.length <= 0) {
                    } else {
                    }
                })
        }

     

    actions파일로 가서 removeCartItem을 작성해준다.

    export function removeCartItem(id){//productid를 파라미터로 받는다. 
        const request = axios.post(`/api/users/removeFromCart?_id=${id}`)
        .then(response => {
            return response.data;
        });
    
        return {
            type: REMOVE_FROM_CART_USER,
            payload: request
        }
    }

     

    users router로 가서 작성해준다.

    const {Product} = require("../models/Product");
    
    router.get('/removeFromCart', auth, (req, res) => {
        //지우려면 user모델에서 찾고 삭제하면 된다.
        User.findOneAndUpdate(
            {id:req.user._id},
            {"$pull":
                {"cart":{"id":req.query._id}}//id로 카트를 찾고, 
            },
            {new:true},//처리 후 업데이트
            (err, userInfo)=>{
                let cart = userInfo.cart;
                let array = cart.map(item =>{
                    return item.id
                })
                Product.find({'_id': {$in: array}}) //하나씩 넣어서 찾고 
                    .populate('writer')
                    .exec((err, cartDetail)=>{
                        return res.status(200).json({//성공하면 카트디테일이랑 카트 다 보내야 한다. 
                            cartDetail,
                            cart
                        })
                    })
            }
        )
    });

     

     

    actions을 마저 완성해주자.

    import axios from 'axios';
    import {
        LOGIN_USER,
        REGISTER_USER,
        AUTH_USER,
        LOGOUT_USER,
        ADD_TO_CART_USER,
        REMOVE_CART_ITEM_USER
    
    } from './types';
    
    export function removeCartItem(id){//productid를 파라미터로 받는다. 
        const request = axios.get(`/api/users/removeFromCart?_id=${id}`)
        .then(response => {
            //처리하고 가져온 데이터를 리덕스에 넣어준다.
            response.data.cart.forEach(item=>{
                //cartdetail에다가 user의 quantity도 가져와야한다.
                response.data.cartDetail.forEach((k,i)=>{
                    if(itemid===k.id){
                        response.data.cartDetail[i].quantity = item.quantity
                    }
                })
            })
            return response.data;
        });
    
        return {
            type: REMOVE_CART_ITEM_USER,
            payload: request
        }

    types랑 reducer에도 넣어주자

    export const REMOVE_CART_ITEM_USER = 'remove_cart_item_user';
    
    import {
        LOGIN_USER,
        REGISTER_USER,
        AUTH_USER,
        LOGOUT_USER,
        ADD_TO_CART_USER,
        GET_CART_ITEMS_USER,
        REMOVE_CART_ITEM_USER
    } from '../_actions/types';
    
            case REMOVE_CART_ITEM_USER :
                return {
                    ...state, 
                    cartDetail: action.payload.cartDetail,
                    userData:{
                        ...state,
                        cart:action.payload.cart
                    }} 

     

    cartpage에 돌아와서 마무리 해준다.

    여기서 상품이 삭제되면 total 도 다시 변경이 되어서 반영되도록 하고

    카트에 물품이 있는지에 따라서 아래 뜨는 페이지도 달라지도록 작성한다. 

     

     

     //보여주는 항목 
        const [ShowTotal, setShowTotal] = useState(false)
        const [ShowSuccess, setShowSuccess] = useState(false)
    
        const calculateTotal = (cartDetail) => {
            let total = 0;
    
            cartDetail.map(item => {
                total += parseInt(item.price, 10) * item.quantity
            });
    
            setTotal(total)
            setShowTotal(true)
        }
    
        //카트에서 상품 삭제
        const removeFromCart = (productId) => {//삭제할 상품아이디를 받는다. 
            //리덕스를 이용하는데, 
            dispatch(removeCartItem(productId))
                .then((response) => {
                    if (response.payload.cartDetail.length <= 0) {
                        setShowTotal(false)
                    } else {
                        calculateTotal(response.payload.cartDetail)//아이템 리스트가 재정비 되었을때
                    }
                })
        }
        
         // const removeFromCart = (productId) => {//삭제할 상품아이디를 받는다. 
        //     //리덕스를 이용하는게 느려서 만약 axios를 이용한다면 이렇게 한다.
        //     dispatch(removeCartItem(productId))
        //         .then(() => {
        //             Axios.get('/api/users/userCartInfo')
        //                 .then(response=>{
        //                     if(response.data.success){
        //                         if (response.payload.cartDetail.length <= 0) {
        //                             setShowTotal(false)
        //                         } else {
        //                             calculateTotal(response.payload.cartDetail)//아이템 리스트가 재정비 되었을때
        //                         }
    
        //                     }else{
        //                         alert('Failed to get cart info')
        //                     }
                            
        //                 })
    
        //         })
        // }
        
        
        
    
                    {ShowTotal ? //total 이 있을 때 
                        <div style={{ marginTop: '3rem' }}>
                            <h2>Total amount: ${Total} </h2>
                        </div>
                        :
                        ShowSuccess ?//total이 없을 때 show가 성공했으면 보여준다.
                            <Result
                                status="success"
                                title="Successfully Purchased Items"
                            /> ://아이템이 장바구니에 없을 때
                            <div style={{
                                width: '100%', display: 'flex', flexDirection: 'column',
                                justifyContent: 'center'
                            }}>
                                <br />
                                <Empty description={false} />
                                <p>No Items In the Cart</p>
    
                            </div>
                    }

     

     

    axios를 이용한다면 user router를 추가해준다.

    router.get('/userCartInfo', auth, (req, res) => {
        User.findOne(
            { _id: req.user._id },
            (err, userInfo) => {
                let cart = userInfo.cart;
                let array = cart.map(item => {
                    return item.id
                })
    
    
                Product.find({ '_id': { $in: array } })
                    .populate('writer')
                    .exec((err, cartDetail) => {
                        if (err) return res.status(400).send(err);
                        return res.status(200).json({ success: true, cartDetail, cart })
                    })
    
            }
        )
    })
    

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

     

Designed by Tistory.