Skip to content

Instantly share code, notes, and snippets.

@SabrinaMarkon
Forked from ryanjyost/App.js
Created March 31, 2019 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save SabrinaMarkon/9ca30948f9b8bf9c1f53d2e3684977b8 to your computer and use it in GitHub Desktop.
Save SabrinaMarkon/9ca30948f9b8bf9c1f53d2e3684977b8 to your computer and use it in GitHub Desktop.
Updated with localStorage methods
import React, { Component } from "react";
import logo from "./logo.svg";
import "./App.css";
class App extends Component {
constructor(props) {
super(props);
this.state = {
newItem: "",
list: []
};
}
componentDidMount() {
this.hydrateStateWithLocalStorage();
// add event listener to save state to localStorage
// when user leaves/refreshes the page
window.addEventListener(
"beforeunload",
this.saveStateToLocalStorage.bind(this)
);
}
componentWillUnmount() {
window.removeEventListener(
"beforeunload",
this.saveStateToLocalStorage.bind(this)
);
// saves if component has a chance to unmount
this.saveStateToLocalStorage();
}
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 });
}
}
}
}
saveStateToLocalStorage() {
// for every item in React state
for (let key in this.state) {
// save to localStorage
localStorage.setItem(key, JSON.stringify(this.state[key]));
}
}
updateInput(key, value) {
// update react state
this.setState({ [key]: value });
}
addItem() {
// create a new item with unique id
const newItem = {
id: 1 + Math.random(),
value: this.state.newItem.slice()
};
// copy current list of items
const list = [...this.state.list];
// add the new item to the list
list.push(newItem);
// update state with new list, reset the new item input
this.setState({
list,
newItem: ""
});
}
deleteItem(id) {
// copy current list of items
const list = [...this.state.list];
// filter out the item being deleted
const updatedList = list.filter(item => item.id !== id);
this.setState({ list: updatedList });
}
render() {
//...all the same
}
}
export default App;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment