bradtraversy / proshop_mern

Shopping cart built with MERN & Redux
1.99k stars 1.18k forks source link

{cartItems.reduce((acc, item) => acc + item.qty, 0)} showing NaN for Subtotal items #85

Closed nikhilsiem closed 3 years ago

nikhilsiem commented 3 years ago

this is my code:

Subtotal ({cartItems.reduce((acc, item) => acc + item.qty, 0)}) items $ {cartItems .reduce((acc, item) => acc + item.qty * item.price, 0) .toFixed(2)} this is giving me NAN values at both the places.

promiselxg commented 3 years ago

can u paste your CartScreen code?

nikhilsiem commented 3 years ago

After implementing removeFromCart, the NaN disappeared. But now when I'm removing anything from the cart, It;s showing Nan and all the images of other items in cart is disappearing.

nikhilsiem commented 3 years ago

import React, { useEffect } from 'react' import { Link } from 'react-router-dom' import { useDispatch, useSelector } from 'react-redux' import { Row, Col, ListGroup, Image, Form, Button, Card } from 'react-bootstrap' import Message from '../components/Message' import { addToCart, removeFromCart } from '../actions/cartActions'

const CartScreen = ({match, location, history }) => { const productId = match.params.id

const qty = location.search ? Number(location.search.split('=')[1]) : 1

const dispatch = useDispatch()

const cart = useSelector(state =>state.cart)
const { cartItems} = cart

useEffect(() => {
    if (productId) {
    dispatch(addToCart(productId, qty))
}
}, [dispatch, productId, qty])

const removeFromCartHandler = (id) => { dispatch(removeFromCart(id)) }

const checkoutHandler = () => { history.push('/login?redirect=shipping') }

return (
    <Row>
        <Col md={8}>
            <h1>Shopping Cart</h1>
            {cartItems.length === 0 ? 
            (<Message>Your cart is empty. <Link to='/'>Go Back</Link></Message>
            ) : (
                <ListGroup variant='flush'>
                    {cartItems.map(item => (
                        <ListGroup.Item key={item.product}>
                            <Row>
                                <Col md={2}>
                                    <Image src={item.image} alt={item.name} fluid rounded />
                                </Col>
                                <Col md={3}>
                                    <Link to={`/product/${item.product}`}>{item.name}</Link>
                                </Col>
                                <Col md={2}>₹{item.price}</Col>
                                <Col md={2}>
                                    <Form.Control as='select' value={item.qty} onChange={(e) =>
                                        dispatch(addToCart(item.product, Number(e.target.value)))}>
                                           {
                                            [...Array(item.countInStock).keys()].map((x) => (
                                                <option key={x + 1} value={x + 1}>{x + 1}</option>

                                            ))
                                            }
                                        </Form.Control>
                                    </Col>
                                    <Col md={2}>
                                        <Button type='button' variant='light' onClick={()=>
                                        removeFromCartHandler(item.product)}>
                                            <i className='fas fa-trash'></i>
                                        </Button>
                                    </Col>
                            </Row>

                        </ListGroup.Item>
                    ))}
                </ListGroup>
            )}

        </Col>
        <Col md={4}>
            <Card>
                <ListGroup variant='flush'>
                    <ListGroup.Item>
                    <h2>
                        Subtotal ({cartItems.reduce((acc, item) => acc + item.qty, 0)})
                        items
                    </h2>
                    ₹
                    {cartItems
                        .reduce((acc, item) => acc + item.qty * item.price, 0)
                        .toFixed(2)}
                    </ListGroup.Item> 
                    <ListGroup.Item>
                        <Button
                            type='button'
                            className='btn-block'
                            disabled={cartItems.length === 0}
                            onClick={checkoutHandler}
                        >
                            Proceed To Checkout
                        </Button>
                    </ListGroup.Item>
                </ListGroup>
            </Card>

        </Col>

    </Row>
)

}

export default CartScreen githb

promiselxg commented 3 years ago

your code snippet look good, the error could actually be from another page.

nikhilsiem commented 3 years ago

would .eslintcache cause any error? @bradtraversy @basir any suggestions?

basir commented 3 years ago

this point is to pass numeric data to addToCart function and you did in this code. clear the cookie to remove previous orderItems and try again. if you still get an error Please clone this repo and run it on your computer. It works.

https://github.com/bradtraversy/proshop_mern/

Then compare your code with this.

nikhilsiem commented 3 years ago

Solved the problem. It was just the cookie causing problem.