SetTimeout ReactJS with arrow function es6

I would like to know how to use setTimeout()in ReactJS because I am doing this:

 timerid = setTimeout( () => this.reqMaq( obj['fkmaqid'] ), 2000 )

and it calls the function twice this.reqMaq().

How to prevent the first call? and just hold the challenge after time?

Here is the Component:

reqMaq (maqid) {
    return fetch(`/scamp/index.php/batchprodpry/${maqid}`, {credentials: 'same-origin'})
      .then(req => {
        if (req.status >= 400) {
          throw new Error("Bad response from server")
        }
        return req.json()
      })
      .then(json => this.processMaqReq(json))
      .catch(function(error) {
        console.log('request failed', error)
      })
  }    

  handleChangeMaq (event) {
    event.preventDefault()
    if (event.target.value.length > 0) {
      let obj = this.state.obj
      obj['fkmaqid'] = VMasker.toPattern(event.target.value, "99-99-99-99")
      // if (timerid) {
      //   clearTimeout(timerid)
      // }
      // timerid = setTimeout(() => {
      //   if (!isRunning) {
      //     this.reqMaq(obj['fkmaqid'])
      //   }
      // }, 2000)
      const fx = () => this.reqMaq( obj['fkmaqid'] )
      timerid = setTimeout( fx, 2000 )
      this.setState({ obj: obj })
    }
  }
  render() {
    return (
      <div className="form-group">
              <label htmlFor="maquina">M&aacute;quina</label>
              <input type="text" className="form-control" id="maquina"
                name="maquina"
                placeholder="Maquina"
                value={this.state.obj['fkmaqid'] || ''}
                onChange={this.handleChangeMaq}
                ref={node => {
                  input1 = node
                }}
                required="required"
              />
            </div>
    )
  }

Thank.

+4
source share
2 answers

Try the following:

if (timerid) {
  clearTimeout(timerid);
}

timerid = setTimeout(() => {
  this.reqMaq(obj['fkmaqid'])
}, 2000);
+15
source

That should do the trick

const fx = () => this.reqMaq( obj['fkmaqid'] )
timerid = setTimeout( fx, 2000 )
+2
source

Source: https://habr.com/ru/post/1651415/


All Articles