wzrd
wzrd

Reputation: 65

How do you persist data in state with react and local storage?

Currently building a shopping cart, one component holds the products, onClick(add to cart) I'd add the item to localstorage, then in another component retrieve and show the items from local storage.

My current set up works but upon refresh, and new when a new item is added it overwrites the old data. I'm assuming on refresh the state resets to empty. How would you implement the data to persist with or without the state?

class ProductsContainer extends Component {
  constructor(props) {
    super(props);
    this.state = { products: [] };
    this.addToCart = this.addToCart.bind(this);
  }

  addToCart = (item) => {
    let productList = this.state.products;
    productList.push({ img: item.img, name: item.name, price: item.price });
    this.setState({ products: productList });
    localStorage.setItem("products", JSON.stringify(productList));
  };

...
...
...

render(){
  return(
    <button className="add-item" onClick={() => this.addToCart(item)}>
  )
});


class ShoppingCart extends Component {
  constructor(props) {
    super(props);
    this.state = { products: [] };
  }

  componentDidMount() {
    const allProducts = localStorage.getItem("products");
    this.setState({ products: JSON.parse(allProducts) });
  }

...
...
...

}

Upvotes: 0

Views: 556

Answers (1)

Mauricio Avenda&#241;o
Mauricio Avenda&#241;o

Reputation: 851

seems you are overwriting the products in the local storage when the page is refreshed and you try to add a new array, to avoid that you could do a little check to the local storage before replacing the previous array:

const products = JSON.parse(localStorage.getItem("products"));
if (products) localStorage.setItem("products", JSON.stringify([...products, product]));
else localStorage.setItem("products", JSON.stringify([product]));

Upvotes: 1

Related Questions