DEV Community

Michael Aufreiter
Michael Aufreiter

Posted on

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

Top comments (1)

Collapse
 
michael_73 profile image
Michael Aufreiter

We've found some answers in this discussion here:

github.com/dminkovsky/use-prosemir...