Created
May 22, 2020 19:47
-
-
Save alx8437/b2477308a87761fc86db20843a7633f0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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