Autosave database after timeout

I want to do an autosave when the user fills out a form in a React component. The ajax call should fire when 3 seconds have passed since the last event onChange

.

My code below is inspired by an instructive article that shows how to accomplish this with setTimeout

and clearTimeout

. But I am doing something wrong in my React implementation - the 3 second delay is not enforced when typing.

Any ideas what is wrong here? Or am I thinking all together is wrong about how to solve this?

class Form extends Component {
  constructor() {
    super();
    this.state = {
      isSaved: false
    };
    this.handleUserInput = this.handleUserInput.bind(this);
    this.saveToDatabase = this.saveToDatabase.bind(this);
  }
  saveToDatabase() {
    var timeoutId;
    this.setState({isSaved: false});
    if (timeoutId) {
        clearTimeout(timeoutId)
    };
    timeoutId = setTimeout( ()  => {
        // Make ajax call to save data.
        this.setState({isSaved: true});
    }, 3000);
  }
  handleUserInput(e) {
    const name = e.target.name;
    const value = e.target.value;
    this.setState({[name]: value});
    this.saveToDatabase();
  }
render() {
  return (
    <div>
      {this.state.isSaved ? 'Saved' : 'Not saved'}
      // My form.
    </div>
  )
}

      

+3


source to share


1 answer


Inside the method, saveToDatabase

you define a new variable and undefined timeoutId

each time you call the method. This is why the operator is if

never called.

Instead, you need to expand the variable and create the class data property in the constructor.



 constructor() {
   super();
   this.state = {
     isSaved: false
   };
   this.timeoutId = null;
   this.handleUserInput = this.handleUserInput.bind(this);
   this.saveToDatabase = this.saveToDatabase.bind(this);
 } 

 saveToDatabase() {
   this.setState({isSaved: false});
   if (this.timeoutId) {
     clearTimeout(this.timeoutId)
   };
   this.timeoutId = setTimeout( ()  => {
     // Make ajax call to save data.
     this.setState({isSaved: true});
   }, 3000);
 }

      

+1


source







All Articles