Autosave logic with React Functional Components
Michael Aufreiter
Posted on January 17, 2021
What is the best way to model a simple autosave logic with Functional components? Using Class Components my logic looked like this:
class MyEditor extends React.Component {
constructor (...args) {
super(...args)
this._debouncedAutosave = debounce(this._save, 1000)
this._saving = false // while saving is in progress
this._scheduled = false
}
onContentChanged() {
this._debouncedAutosave()
}
async _save() {
if (this._saving) {
this._scheduled = true
return // no new saves until current one has finished
}
this._saving = true
await saveArticle(this._getEditorContent())
this._saving = false
if (_scheduled) {
this._scheduled = false
this._save()
}
}
render() {
...
}
}
I failed miserably trying to model this as a Functional Component with useState, useCallback etc.
How would you go about this? Any help much appreciated!
Michael
💖 💪 🙅 🚩
Michael Aufreiter
Posted on January 17, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
undefined Exploring the React component lifecycle: A guide to understanding the different phases.
November 29, 2024