ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 아마존 E-commerce 클론 -17) order Screen 만들기
    NODE.JS 2021. 5. 28. 04:14

     먼저 주문하면 주문아이디에 따라서 상세정보페이지로 가는 라우터를 만들것이다. 

    orderRouter.js

    오직 로그인된 사람만 자기 정보를 볼 수 있게 하기위해서 isAuth미들웨어를 추가한다. 

    orderRouter.get('/:id', isAuth, expressAsyncHandler(async(req, res)=>{
        const order = await Order.findById(req.params.id)
        if(order){
            res.send(order);
        }else{
            res.status(404).send({message:'Order Not Found'})
        }
    }))
    
    

     

    이제 프론트엔드로 가서 이 API를 사용하도록 하자. 

    이제 OrderScreen.js를 만들 것인데 디테일 페이지의 정보는 

    PlaceOrderScreen.js와 매우 비슷하므로 복사해서 일부수정하는 방식으로 나타내자.

    디스패치도 일단 해준다.  

    import React ,{useEffect} from 'react'
    import { useDispatch } from 'react-redux'
    import CheckoutSteps from '../components/CheckoutSteps'
    import {Link} from 'react-router-dom';
    import LoadingBox from '../components/LoadingBox'
    import MessageBox from '../components/MessageBox'
    
    function OrderScreen(props) {
        
        const orderId = props.match.params.id;
    
        const dispatch = useDispatch()
    
        useEffect(() => {
            dispatch(detailsOrder(orderId));
        }, [dispatch, orderId])
    
    
        return (
    ...생략
    }
    
    export default OrderScreen
    

     

    orderConstants.js

    export const ORDER_DETAILS_REQUEST = 'ORDER_DETAILS_REQUEST'
    export const ORDER_DETAILS_SUCCESS = 'ORDER_DETAILS_SUCCESS'
    export const ORDER_DETAILS_FAIL = 'ORDER_DETAILS_FAIL'

     

     

    orderActions.js

    export const detailsOrder = (orderId)=> async (dispatch, getState)=>{
        dispatch({
            type:ORDER_DETAILS_REQUEST,
            payload:orderId
        })
        try{
            const {userSignin : {userInfo}} = getState();
            const{data} = await axios.get(`/api/orders/${orderId}`, {
                headers:{
                    Authorization:`Bearer ${userInfo.token}`
                }
            })
            dispatch({
                type:ORDER_DETAILS_SUCCESS,
                payload:data
            })
    
        }catch(error){
            const message = error.response && error.response.data.message
            ? error.response.data.message
            : error.message;
            dispatch({
                type:ORDER_DETAILS_FAIL,
                payload:message
            })
        }
    }

     

     

    orderReducers.js

    export const orderDetailsReducer = (state = {loading:true, order:{}}, action) =>{
        switch(action.type){
            case ORDER_DETAILS_REQUEST:
                return {loading:true}
            case ORDER_DETAILS_SUCCESS:
                return {loading:false, order:action.payload}
            case ORDER_DETAILS_FAIL:
                return {loading:false, error:action.payload}
            default:
                return state;
        }
    }
    
    

     

    store.js

    import { orderCreateReducer, orderDetailsReducer } from './reducers/orderReducers';
    const reducer = combineReducers({
        productList: productListReducer,
        productDetails : productDetailsReducer,
        cart:cartReducer,
        userSignin: userSigninReducer,
        userRegister: userRegisterReducer,
        orderCreate:orderCreateReducer,
        orderDetails:orderDetailsReducer
        
    
    })

     

    orderscreen을 다음과 같이 수정해준다. 

    import React ,{useEffect} from 'react'
    import { useDispatch } from 'react-redux'
    import CheckoutSteps from '../components/CheckoutSteps'
    import {Link} from 'react-router-dom';
    import LoadingBox from '../components/LoadingBox'
    import MessageBox from '../components/MessageBox'
    import { detailsOrder } from '../actions/orderActions';
    
    function OrderScreen(props) {
        
        const orderId = props.match.params.id;
        const orderDetails = useSelector(state => state.orderDetails)
        const {order, loading, error} = orderDetails;
    
        const dispatch = useDispatch()
    
        useEffect(() => {
            dispatch(detailsOrder(orderId));
        }, [dispatch, orderId])
    
    
        return loading? (<LoadingBox></LoadingBox>):
            error? (<MessageBox variant = 'danger'>{error}</MessageBox>)
            :(
            <div>
                <h1>Order {order._id}</h1>
                <div className="row top">
                    <div className="col-2">
                        <ul>
                            <li>
                                <div className="card card-body">
                                    <h2>Shipping</h2>
                                    <p>
                                        <strong>Name:</strong>{order.shippingAddress.fullName}<br/>
                                        <strong>Address:</strong>{order.shippingAddress.address},{order.shippingAddress.city},{order.shippingAddress.postalCode},{order.shippingAddress.country}
                                    </p>
                                </div>
                            </li>
                            <li>
                                <div className="card card-body">
                                    <h2>Payment</h2>
                                    <p>
                                        <strong>Method:</strong>{order.paymentMethod}<br/>
                                    </p>
                                </div>
                            </li>
                            <li>
                                <div className="card card-body">
                                    <h2>Order Items</h2>
                                    <ul>
                                        {order.orderItems.map(item=>(
                                                <li key = {item.product}>
                                                    <div className="row">
                                                        <div>
                                                            <img src={item.image} alt={item.name} className="small"/>
                                                        </div>
                                                        <div className="min-30">
                                                            <Link to={`/product/${item.product}`}>{item.name}</Link>
                                                        </div>
                                                        <div>
                                                             {item.qty} x ${item.price} = ${item.qty * item.price}
                                                        </div>
                                                    </div>
                                                </li>
                                            ))
                                        }
                                    </ul>
                                </div>
                            </li>
                        </ul>
                    </div>
                    <div className="col-1">
                        <div className="card card-body">
                            <ul>
                                <li>
                                    <h2>Order Summary</h2>
                                </li>
                                <li>
                                    <div className="row">
                                        <div>Items</div>
                                        <div>${order.itemsPrice.toFixed(2)}</div>
                                    </div>
                                </li>
                                <li>
                                    <div className="row">
                                        <div>Shipping</div>
                                        <div>${order.shippingPrice.toFixed(2)}</div>
                                    </div>
                                </li>
                                <li>
                                    <div className="row">
                                        <div>Tax</div>
                                        <div>${order.taxPrice.toFixed(2)}</div>
                                    </div>
                                </li>
                                <li>
                                    <div className="row">
                                        <div>
                                            <strong>Order Total</strong>
                                        </div>
                                        <div>
                                            <strong>${order.totalPrice.toFixed(2)}</strong>
                                        </div>
                                    </div>
                                </li>
                            
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
            
        )
    }
    
    export default OrderScreen
    

     

     

    app.js에 페이지 추가.

    import OrderScreen from './screens/OrderScreen';
                  <Route path="/order/:id" component={OrderScreen} exact></Route>
    

     

     

     

     

     

     

     

     

    주문이 배송되었는지 확인하는 구간을 넣어주자. 

                                <div className="card card-body">
                                    <h2>Shipping</h2>
                                    <p>
                                        <strong>Name:</strong>{order.shippingAddress.fullName}<br/>
                                        <strong>Address:</strong>{order.shippingAddress.address},{order.shippingAddress.city},{order.shippingAddress.postalCode},{order.shippingAddress.country}
                                    </p>
                                    {
                                        order.isDelivered? <MessageBox variant="success">Delivered at {order.deliveredAt}</MessageBox>
                                        :<MessageBox variant="danger">Not Delivered</MessageBox>
                                    }
                                </div>

     

     

     

    돈이 지불 되었는지도 확인하는 구간을 만들어주자. 

                                <div className="card card-body">
                                    <h2>Payment</h2>
                                    <p>
                                        <strong>Method:</strong>{order.paymentMethod}<br/>
                                    </p>
                                    {
                                        order.isPaid? <MessageBox variant="success">Paid at {order.paidAt}</MessageBox>
                                        :<MessageBox variant="danger">Not Paid</MessageBox>
                                    }
                                </div>

     

     

     

     

     

     

     

     

     

     

     

Designed by Tistory.