0

There is a function that adds objects product to products in state

addProductToCart(productId, productName)
{
  var product = {
    id: productId,
    name: productName,
  };

  this.setState({
    products: {
      ...this.state.products,
      [product.id]: product
    }
  });
}

but these objects are sorted by [product.id]. How do I sort them in the order they are added to the cart?

Sgt Maddonut
  • 759
  • 2
  • 8
  • 20
  • Any particular reason why are you keeping items as unordered map instead of array? If you had a state in the shape of `[product1, product2]` and reducer which would add it like so `[...this.state.products, newProduct]` then they would be ordered as they are – Jacek Lipiec Nov 26 '18 at 09:16
  • I use it because it is easy to remove a `product` from `products` using `delete this.state.products[id];` Is there something similar for arrays? – Sgt Maddonut Nov 26 '18 at 09:19
  • Not THAT easy, but simple enough. Since your `id` is a key, we can treat is uniquely; and we can use `filter` on a array to do the job. let's use function defined as `function productsWithoutGivenIdPredicate(id) {return (product)=>product.id!==id}}` and use it like so: `var productsWithDeletedItem = productsInBasket.filter(productsWithoutGivenIdPredicate(__SOMEID__))` – Jacek Lipiec Nov 26 '18 at 10:09

2 Answers2

0

maintain one more array ids in which, you can append the productIds as they are added :

addProductToCart(productId, productName)
{
  var product = {
    id: productId,
    name: productName,
  };

  this.setState({
    products: {
      ...this.state.products,
      [product.id]: product
    },
    productIds : [...ids, product.id]
  });
}

You can then iterate over the array to retrieve the product in the order of their insertion.

Easwar
  • 5,132
  • 1
  • 11
  • 21
0

If you read this objects are by default key value pairs,

You have 2 options you can use @Easwar solution or you can use array instead to store. As far as I see your strucutre there is nothing wrong in using the array structure for your requirement.

You should restructure your state like this

 constructor() {
    super();
    this.addProductToCart = this.addProductToCart.bind(this);
    this.state = {
      products: []
    };
  }

  addProductToCart() {
    productsId--;
    var product = {
      id: productsId,
      name: 'test',
    };   

    this.setState({
      products: [...this.state.products,product]      
    });
  }

Demo

As I can see you have a problem getting removed object from array you can use this easily

removefromCart(value) {

    var array = [...this.state.products]; // make a separate copy of the array
    var index = array.findIndex(a => a.id === value);
    if (index !== -1) {
      array.splice(index, 1);
      this.setState({ products: array });
    }
  }
Just code
  • 13,553
  • 10
  • 51
  • 93