2

I'm building a terribly flawed e-commerce application using React just for fun and I'm trying to figure out how to set state on a certain object once it's pushed into an array.

I have a cart array where I push the items that I added from my initial items array which holds all my products.

The iffy thing is that I have stock on products. So let's say my chocolate product has 5 in stock and every time I push that the chocolate object, it piles on and adds the same item in the cart as so:

enter image description here

I want to be pushing the chocolates object to the cart array but I don't want to render a duplicate if it's already there. Instead I want to achieve something where the chocolate object is added but the quantity of it is changed accordingly every time it's added. It would look something like this:

enter image description here

How can I achieve something like this? Maybe a check to see if that object is already added to the cart array and if it is then instead of rendering a duplicate, just push the values and update a quantity of that item?

Been stuck for hours and would greatly appreciate some hints.

class App extends Component {
  state = {
    cart: [],
    items: [
      { id: uuid(), name: 'chocolate', price: 10, remaining: 5 },
      { id: uuid(), name: 'strawberry', price: 50, remaining: 10 },
      { id: uuid(), name: 'banana', price: 43, remaining: 20 }
    ],
    total: 0,
    addToCartMessage: false,
    removeFromCartMessage: false,
    searchTerm: ''
  }

  addItem = item => {
    const { cart, items, total } = this.state

    cart.push({ id: item.id, name: item.name, price: item.price })

    const remaining = item.remaining--    

    const totalPrice = cart.reduce((a, b) => a + b.price, 0)

    this.setState({
      total: totalPrice, 
      cart,
      addToCartMessage: true,
      ...items, remaining
    })
  }

  removeItem = cartItems => { 
    const { items, cart, total } = this.state

    const removeItem = cart.filter(item => item.id !== cartItems.id)

    const itemId = items.find(item => item.name === cartItems.name).remaining++

    this.setState({
      removeFromCartMessage: true,
      total: total - cartItems.price,
      cart: removeItem, 
      ...items, remaining: itemId 
    })
  }

  render() {
    const { cart, items, total, addToCartMessage, removeFromCartMessage } = 
    this.state

    if (addToCartMessage || removeFromCartMessage) {
      setTimeout(() => {
        this.setState({ 
          addToCartMessage: false, 
          removeFromCartMessage: false 
        })
      }, 1000)
    }

    const filteredItems = items.filter(item => 
      item.name.includes(this.state.searchTerm))

    return (
      <div className="App">
        {cart.length === 0 ? <h3>No items in cart</h3> : (
          <div>
            <h1>Cart:</h1>
            {cart.map(items => (
              <div key={items.id}>
                <h1>{items.name} x 3</h1>
                <p>${items.price}</p>
                <button onClick={() => this.removeItem(items)}>Remove From Cart</button>
              </div>
            ))}
          </div>
        )}

        <hr />

        <input 
          type="text"
          placeholder="Search for an item..." 
          onChange={e => this.setState({ searchTerm: e.target.value })} 
          value={this.state.searchTerm} 
        />

        {filteredItems.map(item => (
          <div key={item.id}>
            <h1>{item.name}</h1>
            <p>Price: ${item.price}</p>
            {item.remaining === 0 ?  <p>Sold Out</p> : (
              <div>
                <p>Remaining: {item.remaining}</p>
                <button onClick={() => this.addItem(item)}>Add To Cart</button>
              </div>
            )}
          </div>
        ))}

        { total !== 0 ? <h1>Total ${total}</h1> : <h1>Total $0</h1> }
        { addToCartMessage && <h1>Item successfully added!</h1> }
        { removeFromCartMessage && <h1>Item successfully removed!</h1> }
      </div>
    )
  }
}

export default App

3 Answers 3

3

Store your products in a regular object by id.

1: {
    id: 1,
    name: 'chocolate'
}

Store your cart as an array of IDs.

[1, 1, 1]

In your component, group IDs cart array by ID to get the count, and look up cart object by ID to get its data.

Computed data should be computed, not stored.

Here's some completely untested, unlinted, code showing the calculations done in the render function:

class App extends Component {
    state = {
        cart: [],
        items: [
            { id: uuid(), name: 'chocolate', price: 10, available: 5 },
            { id: uuid(), name: 'strawberry', price: 50, available: 10 },
            { id: uuid(), name: 'banana', price: 43, available: 20 }
        // Convert to an object of { id: { id, name, price } }
        ].reduce((memo, item) => ({
            ...memo,
            [item.id]: item
        }), {}),
    }

    addItem = id => {
        const { cart, } = this.state

        this.setState({
            cart: [ ...cart, id ]
        })
    }

    removeItem = removeId => {
        const { cart, } = this.state
        this.setState({
            cart: cart.filter(({ id }) => id !== removeId)
        })
    }

    render() {
        const { cart, items, total, addToCartMessage, removeFromCartMessage } = this.state

        // Given an array of item IDs in our cart, group them into an object
        // with the total count and price for each item, and overall count
        const accumulatedItems = items.reduce((memo, item) => {
            const { id, price } = item;
            const { count, price, } = memo[id] || {};
            return {
                ...memo,
                cartTotal: memo.cartTotal + price,
                [id]: {
                    count: (count || 0) + 1,
                    total: (price || 0) + price,
                }
            };
        // Starting object to reduce
        }, {
            cartTotal: 0,
        });

        return (
            <div className="App">
                {cart.length === 0 ? <h3>No items in cart</h3> : (
                    <div>
                        <h1>Cart:</h1>
                        {Object.keys(accumulatedItems).sort().map(id => (
                            <div key={id}>
                                <h1>{items[id].name} x {accumulatedItems[id].total}</h1>
                                <p>${accumulatedItems[id].total}</p>
                                <button onClick={() => this.removeItem(id)}>Remove From Cart</button>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        );
    }
}

Juggling computed data, and mutating state like remaining, adds significant logic complexity to your app. You should only start worrying about trying to store/cache/memoize computed state once there are performance issues. Calculating totals in the render function is a fine first pass.

In React in the wild, there are solutions like reselect, which don't require redux technically. They're just caching functions that take in a given state, and produce a computed output, and only re-calculate the output if the input changes.

Sign up to request clarification or add additional context in comments.

3 Comments

Concise and very nice answer. I really like the last sentence. Experience is needed times like this :)
Thank-you for the response. Would you be kind enough to maybe give a little code snippet of you explanation? I'm not sure I'm on the same page as you. I would really appreciate it. :)
@Andy Ray For the accumulatedItems part, did you mean to do Object.keys(items).map() since you changed the state of items from an array to an object in the component state? I've changed it to that but when I add items to my cart, it adds all of them at once.
1

Maybe you can do it how you think and explain in your question. There are multiple ways of doing this and everyone do it how they like it or how easy they do and maintain it.

  • Instead of inserting the item itself maybe you can hold an object for each item in your array with item's unique id. That object also could hold quantity. Then you can generate card info via this unique id.

Example:

cart: [
          { id: uniqeId, quantiy: 1 },
          { id: uniqeId, quantiy: 6 },
      ]

After adding an item to card, you can go and just alter the related object's quantity. But for this you have to find the item in this array, then alter the quantity as you guess.

  • You can have item ids in your cart object (not array this time) as an array but this time you separate quantity and hold it as an object by item ids. So, after adding the item to cart's id array list, you also go and alter quantity of item's object. With this method you don't have to struggle finding anything but you need to alter two piece of information.

Like:

cart: {
          ids: [ uniqueId, uniqueId ],
          quantity: { uniqueId: 1, uniqueId: 6 }
      } 
  • Or you can do how you describe, just add the item but before doing this check if the item is already there. For example filtering by id. But, with this technique there might be some glitches. When you add items like this, for example with price, remaining etc, you also have to maintain your cart state with your item state. For instance what will happen when you want to change an item's price? Or what if there is another way (somehow) altering the remaining other then adding items into cart? But, if you play only with id's you can extract those information from your single state: items.

But I'm also a learner, maybe there are way better methods apart from those. I haven't written a cart yet, but if I did it I would use the second method maybe.

By the way, do not use push to alter your state. This mutates your state and it is not advisable. Use something like concat or spread operator to create a new state.

item = { foo: bar, fizz: buzz }
// now setting state
cart: [ ...this.state.cart, item ]

And try to use a callback function in setState (since it is an async operation) if your state change depends on the previous state.

this.setState( prevState => ( {
    cart: [ ...prevState.cart, item ],
} ) )

4 Comments

Thanks for the detailed response, I really appreciate it. With the code cart: { ids: [ uniqueId, uniqueId ], quantity: { uniqueId: 1, uniqueId: 6 } } do you mean to concat the item info so name, id, remaining into the ids array or just the items id? I wasn't really sure what you meant there.
Just the ids. For the other information you can retrieve it using ids. And, if you hold your state as @Andy Ray showed, it will be easier to retrieve the related item.
I'm not really sure how to actually grab the info. I have my state set up like @Andy Ray suggested but I just don't understand how I can get the info based on id.
Your ids are unique. So in your code this.state.items[id] will be the related item and this.state.items[id].name is item's name. With this technique you don't have to iterate over an array and try to find your item. Just use its unique id and grab the info like that. But, if you want to render whole items(not cart) you need to use something like Object.keys and map it as @Andy Ray used in his code. For cart, map the array, use the id, grab the info from state.
0

Using @devserkan suggestion of restructuring the cart state and @Andy Ray's suggestion of restructuring the items state, I set up my state to look like this:

state = {
  items: {
    1: {
      id: 1, name: 'chocolate', price: 10, available: 5
    },  

    2: {
      id: 2, name: 'strawberry', price: 10, available: 10
    },

    3: {
      id: 3, name: 'banana', price: 10, available: 20
    }
  }

  cart: {
    ids: [],
    quantity: { 1: 0, 2: 0, 3: 0 }
  }
}

I then went and rendered out the items and added an onClick function (addItem) to handle some setState calls:

render() {
  const { cart, items } = this.state

return (
  <div>
    <h1>Shopping Area</h1>
    {Object.values(items).map(item => (
      <div key={item.id}>
        <h2>{item.name}</h2>
        <h2>{item.price}</h2>
        <button onClick={() => this.addItem(item)}>Add To Cart</button>
      </div>
    ))}

In my addItem function, I went ahead and set the state of cart so that I push the item id, and update the quantity on that id as well:

addItem = item => {
  const { cart, items } = this.state

  this.setState({
    cart: {
      ...cart,
      // Push item id to ids array inside cart state
      ids: [...cart.ids, item.id],
      quantity: {
        ...cart.quantity,
        // Update quantity of the specific id pushed by 1
        [item.id]: cart.quantity[item.id] + 1
      }
    }
  })
}

Finally I had to render the cart section: I did so by checking to see if the cart.ids array wasn't empty and made another check to only render the item that has a quantity greater than 0. If we didn't make that check, every time we push an item, it will add all 3 at once and we only want that specific item to show.

 {cart.ids.length !== 0 ? Object.keys(items).map(id => (
   <div key={id}>
     // Check to see if quantity for that item is > 0
     {cart.quantity[id] > 0 && (
       <h1>{items[id].name} x {cart.quantity[id]}</h1>
     )}
   </div>
 )) : <h1>No Items In Your Cart</h1>}

Full Code (Without Price / Remaining)

export default class App extends Component {
  state = {
    cart: {
      ids: [],
      quantity: {
        1: 0, 
        2: 0, 
        3: 0
      }
    },

    items: {
      1: {
        id: 1, name: 'chocolate', price: 10, available: 5
      },  

      2: {
        id: 2, name: 'strawberry', price: 10, available: 10
      },

      3: {
        id: 3, name: 'banana', price: 10, available: 20
      }
    }
  }

  addItem = item => {
    const { cart, items } = this.state

    this.setState({
      cart: {
        ...cart,
        ids: [...cart.ids, item.id],
        quantity: {
          ...cart.quantity,
          [item.id]: cart.quantity[item.id] + 1
        }
      }
    })
  }

  removeItem = removeId => {
    const { cart } = this.state
    this.setState({
      cart: cart.filter(({ id }) => id !== removeId)
    })
  }

  render() {
    const { cart, items, total, addToCartMessage, removeFromCartMessage } = 
    this.state

    return (
      <div className="App">
        <h1>Shopping Area</h1>
        {Object.values(items).map(item => (
          <div key={item.id}>
            <h2>{item.name}</h2>
            <h2>{item.price}</h2>
            <button onClick={() => this.addItem(item)}>Add To Cart</button>
          </div>
        ))}

        <hr style={{'marginTop': '200px'}} />

        <h1>Cart</h1>

        {cart.ids.length !== 0 ? Object.keys(items).map(id => (
          <div key={id}>
            {cart.quantity[id] > 0 && (
              <h1>{items[id].name} x {cart.quantity[id]}</h1>
            )}
          </div>
        )) : <h1>No Items In Your Cart</h1>}
      </div>
    )
  }
}

Big thanks to @Andy Ray and @devserkan for the suggestions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.