How to store multiple things in the local storage?

I’ve created a webshop and I would like to store the products themselves, subtotal, tax and total in the local storage. Now the problem is that I can store the products for instance but not everything (product, subtotal, tax and total).

addToCart = (id) => {
      let tempProducts = [...this.state.products];
      const index = tempProducts.indexOf(this.getItem(id));
      const product = tempProducts[index];
      product.inCart = true;
      product.count = 1;
      const price = product.price;
      product.total = price;
      this.setState(() => {
        return {products:tempProducts, cart:[...this.state.cart,
        product] };
      }, () => { 
                 this.addTotals();
                 const unified = Object.assign({}, {cart: this.state.cart}, {subTotal: this.state.cartSubTotal})
                 localStorage.setItem('myObject', JSON.stringify(unified))
               });
  };

I tried this (unified object) but I think I have a mistake in the componentDidMount function. Furthermore, the Object.assign() only takes two arguments as I’ve heard.

componentDidMount() {
    this.setProducts();
    this.setState({
                  unified : !localStorage.getItem('myObject') 
                          ? []
                          : JSON.parse(localStorage.getItem('myObject'))
                  })
  };

Whole code:

import React, { Component } from 'react';
import {storeProducts, detailProduct} from './data';

const ProductContext = React.createContext();
//Provider
//Consumer

class ProductProvider extends Component {
  state = {
      products: [],
      detailProduct: detailProduct,
      cart: [],
      modalOpen: false,
      modalProduct: detailProduct,
      cartSubTotal: 0,
      cartTax: 0,
      cartTotal: 0
  };

  componentDidMount() {
    this.setProducts();
    this.setState({
                  unified : !localStorage.getItem('myObject') 
                          ? []
                          : JSON.parse(localStorage.getItem('myObject'))
                  })
  };

  setProducts = () => {
    let tempProducts = [];
    storeProducts.forEach(item => {
      const singleItem = { ...item };
      tempProducts = [...tempProducts, singleItem];
    })
    this.setState(() => {
      return {products: tempProducts}
    })
  };

  getItem = (id) => {
    const product = this.state.products.find(item => item.id === id);
    return product;
  };

  handleDetail = (id) => {
      const product = this.getItem(id);
      this.setState(() => {
        return {detailProduct:product}
      })
  };

  addToCart = (id) => {
      let tempProducts = [...this.state.products];
      const index = tempProducts.indexOf(this.getItem(id));
      const product = tempProducts[index];
      product.inCart = true;
      product.count = 1;
      const price = product.price;
      product.total = price;
      this.setState(() => {
        return {products:tempProducts, cart:[...this.state.cart,
        product] };
      }, () => { 
                 this.addTotals();
                 const unified = Object.assign({}, {cart: this.state.cart}, {subTotal: this.state.cartSubTotal})
                 localStorage.setItem('myObject', JSON.stringify(unified))
               });
  };

  openModal = (id) => {
    const product = this.getItem(id);
    this.setState(() => {
      return {modalProduct:product, modalOpen:true}
    });
  };

  closeModal = () => {
    this.setState(() => {
      return {modalOpen:false}
    });
  };

  increment = (id) => {
    let tempCart = [...this.state.cart];
    const selectedProduct = tempCart.find(item => item.id === id);

    const index = tempCart.indexOf(selectedProduct);
    const product = tempCart[index];

    product.count = product.count + 1;
    product.total = product.count * product.price;

    this.setState(() => {
      return{cart: [...tempCart]}
    }, () => {
      this.addTotals()
    })
  };

  decrement = (id) => {
    let tempCart = [...this.state.cart];
    const selectedProduct = tempCart.find(item => item.id === id);

    const index = tempCart.indexOf(selectedProduct);
    const product = tempCart[index];

    product.count = product.count - 1;

    if(product.count === 0) {
      this.removeItem(id);
    }
    else {
      product.total = product.count * product.price;
    }

    this.setState(() => {
      return{cart: [...tempCart]}
    }, () => {
      this.addTotals()
    })
  };

  removeItem = (id) => {
    let tempProducts = [...this.state.products];
    let tempCart = [...this.state.cart];

    tempCart = tempCart.filter(item => item.id !== id);

    const index = tempProducts.indexOf(this.getItem(id));
    let removedProduct = tempProducts[index];
    removedProduct.inCart = false;
    removedProduct.count = 0;
    removedProduct.total = 0;

    this.setState(() => {
      return {
        cart: [...tempCart],
        products: [...tempProducts]
      }
    }, () => {
      this.addTotals();
    })
  };

  clearCart = () => {
    this.setState(() => {
      return { cart: [] }
    }, () => {
      this.setProducts();
      this.addTotals();
    });
  };

  addTotals = () => {
    let subTotal = 0;
    this.state.cart.map(item => (subTotal += item.total));
    const tempTax = subTotal * 0.1;
    const tax = parseFloat(tempTax.toFixed(2));
    const total = subTotal + tax;
    this.setState(() => {
      return {
        cartSubTotal:subTotal,
        cartTax:tax,
        cartTotal:total
      }
    })
  };

  render() {
    return (
      <ProductContext.Provider 
        value={{
          ...this.state,
          handleDetail: this.handleDetail,
          addToCart: this.addToCart,
          openModal: this.openModal,
          closeModal: this.closeModal,
          increment: this.increment,
          decrement: this.decrement,
          removeItem: this.removeItem,
          clearCart: this.clearCart
        }}>
        {this.props.children}
      </ProductContext.Provider>
    )
  }
}

const ProductConsumer = ProductContext.Consumer;

export {ProductProvider, ProductConsumer};

Well for starters:

[] is not an empty object, it’s an empty array. You meant {}.

False.

You can store multiple things in a single json object then store that under a single localStorage key or you can store things under multiple keys.

I can’t find the issue in your code. If it’s there please only post the relevant code.

The problem is either here somewhere:

componentDidMount() {
    this.setProducts();
    this.setState({
                  unified : !localStorage.getItem('myObject') 
                          ? {}
                          : JSON.parse(localStorage.getItem('myObject'))
                  })
  };

or here:

addToCart = (id) => {
      let tempProducts = [...this.state.products];
      const index = tempProducts.indexOf(this.getItem(id));
      const product = tempProducts[index];
      product.inCart = true;
      product.count = 1;
      const price = product.price;
      product.total = price;
      this.setState(() => {
        return {products:tempProducts, cart:[...this.state.cart,
        product] };
      }, () => { 
                 this.addTotals();
                 const unified = Object.assign({}, {cart: this.state.cart}, {subTotal: this.state.cartSubTotal})
                 localStorage.setItem('myObject', JSON.stringify(unified))
               });
  };

because these are the only places where I made changes. The problem is that it empties the cart on refresh although it should display everything from product to prices

This is also interesting because myCart should not appear at all to my understanding:

localStorage will stay until it’s cleared. Nothing in this code is setting a myCart key in localStorage.

If you clear it, I doubt it will show back up. This looks like some old code you were working with before.

Ok, it does not appear anymore. But I still have no idea what’s wrong with the code.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.