Skip to content

Instantly share code, notes, and snippets.

@alx8437
Created May 22, 2020 19:47
Show Gist options
  • Save alx8437/b2477308a87761fc86db20843a7633f0 to your computer and use it in GitHub Desktop.
Save alx8437/b2477308a87761fc86db20843a7633f0 to your computer and use it in GitHub Desktop.
class App extends React.Component {
state = {
todolists: [],
};
newTodoListId = 0;
addTodoList = (title) => {
let newTodoList = {id: this.newTodoListId, title: title};
let newTodoLists = [...this.state.todolists, newTodoList];
this.setState((state) => {
return {todolists: newTodoLists}
}, this.stateSaveLocalStorage);
this.newTodoListId += 1
};
componentDidMount() {
this.restoreState()
}
stateSaveLocalStorage = () => {
let stateAsString = JSON.stringify(this.state);
localStorage.setItem('ourstatetdlist', stateAsString)
};
restoreState = () => {
let state = {
todolists: [],
};
let stateAsString = localStorage.getItem('ourstatetdlist');
if (stateAsString != null) {
state = JSON.parse(stateAsString)
}
this.setState(state, ()=> this.state.todolists.forEach(td => {
if (td.id > this.newTodoListId) {
this.newTodoListId = td.id + 1;
}
}))
};
render() {
let todolists = this.state.todolists.map(td => <TodoList key={td.id} id={td.id} title={td.title} />)
return (
<div>
<AddNewItemForm
addItem={this.addTodoList}
/>
<div className="App">
{todolists}
</div>
</div>
)
}
}
export default App
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment