react-shopping-cart
react-shopping-cart copied to clipboard
Support local storage ?
Can you make it support local storage? because now if we refresh after adding to cart, all my items are cleared.
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!
Great. Thanks