Search code examples
reactjsreduxreact-state-management

React/Redux Ecommerce State management design question?


I'm following a React/Redux MERN tutorial and there was a discussion about the add to Cart functionality in the tutorial being overly complicated or incorrect.

Can someone who understands proper design and state management for React tell me the pros/cons for each method?

Method 1: Click "Add to Cart" on product screen. The product ID/QTY is passed to your action creator and the reducer will store the product info based on the ID, as well as qty. When going to domain.com/cart, the cartScreen will populate the cart based on the cartReducer state.

const addToCartHandler = () => {
        dispatch(addToCart(product._id, qty))
        props.history.push('/cart')
    }

Method 2: (This is the tutorial method) Click "Add to Cart" on product screen. The AddtoCartHandler redirects to domain.com/cart/ID?qty=1 cartScreen component has useEffect which will dispatch cart action creator and pull ID/Qty from the URL params.

    const productId = match.params.id
    const qty = location.search ? Number( location.search.split('=')[1]) : 1
     
    useEffect(() => {
    if(productId){
     dispatch(addToCart(productId, qty))
    }
    }, [dispatch, productId, qty])

The complaint from students was that method 2 is overly complicated and broken. A student reviewed "When you add an item to cart, you can't change that item's quantity. The reason is we are taking the quantity value (qty) from the query param. So if you try changing the value and refresh the page, the useEffect function will use the productId and qty value to reset the product quantity to the amount originally added to the cart.

Why do it this way? Why not just dispatch addToCart when the user clicks on the Add To Cart button and just show whatever is in the cart state in the CartScreen? Using query strings just makes it overly complicated and bug prone."

As a beginner, I am unsure why method 1 or 2 would be better than the other one and in which case. Before I watched the lecture, I tried to think of doing it myself and wrote pseudocode. I did it method 1. When the instructor started using URL parameters to dispatch, I thought maybe that's better if you have to keep track of the URL and URL history somehow?

THoughts?


Solution

  • Both approaches will work. The first approach is cleaner than the second. Most probably, the tutorial is doing something with the URL they are getting, I assume. Not sure what, but you expose product ID and quantity in URL. URL may be used as a return URL after going to a third-party payment site or feeding values to that site.