sivadass / react-shopping-cart

Easily integrate React Shopping Cart into your existing website without using Redux.
https://sivadass.github.io/react-shopping-cart/
MIT License
576 stars 259 forks source link

Support local storage ? #21

Open malithmcr opened 5 years ago

malithmcr commented 5 years ago

Can you make it support local storage? because now if we refresh after adding to cart, all my items are cleared.

sivadass commented 5 years ago

Yeah we can do it, for time being, you can refer this component from one of my other project:

componentDidMount() {
    this.hydrateStateWithLocalStorage();
  }

  handleAddNew = (id, message, isCompleted) => {
    let newNote = { id, message, isCompleted };
    let notes = [...this.state.notes, newNote];
    this.setState({ notes });
    localStorage.setItem("notes", JSON.stringify(notes));
  }

  handleStatusUpdate = (id, isCompleted) => {
    let notes = [...this.state.notes];
    let index = notes.findIndex(item => item.id === id);
    notes[index].isCompleted = isCompleted;
    this.setState({ notes });
    localStorage.setItem("notes", JSON.stringify(notes));
    console.log(JSON.parse(localStorage.getItem('notes')), null, 2);
  }

  handleMessageUpdate = (id, message) => {
    let notes = [...this.state.notes];
    let index = notes.findIndex(item => item.id === id);
    notes[index].message = message;
    this.setState({ notes });
    localStorage.setItem("notes", JSON.stringify(notes));
  }

  handleDelete = (id) => {
    let notes = [...this.state.notes];
    let index = notes.findIndex(item => item.id === id);
    notes.splice(index, 1);
    this.setState({ notes });
    localStorage.setItem("notes", JSON.stringify(notes));
  }

  hydrateStateWithLocalStorage() {
    // for all items in state
    for (let key in this.state) {
      // if the key exists in localStorage
      if (localStorage.hasOwnProperty(key)) {
        // get the key's value from localStorage
        let value = localStorage.getItem(key);

        // parse the localStorage string and setState
        try {
          value = JSON.parse(value);
          this.setState({ [key]: value });
        } catch (e) {
          // handle empty string
          this.setState({ [key]: value });
        }
      }
    }
}

I will update the same feature in react-shopping-cart in few days!

malithmcr commented 5 years ago

Great. Thanks