Autosave logic with React Functional Components

michael_73

Michael Aufreiter

Posted on January 17, 2021

Autosave logic with React Functional Components

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() {
    ...
  }
}
Enter fullscreen mode Exit fullscreen mode

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_73
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