gamer
gamer

Reputation: 5863

reactjs call a function continuosly after recieving callback

I have a react component like:

class BodyContent extends Component {

    componentDidMount() {
       const { actions } = this.props

        var timerID = setInterval(function() {
            actions.upload_image()
        }, 5000)


    }

My upload_image function contains post request to an api. When response is received I want it to call the function again.

I want to call the function contnuosly only after my upload_image has finised successfully.

How cam I able to do this ??

Upvotes: 0

Views: 50

Answers (2)

Olivier Boissé
Olivier Boissé

Reputation: 18113

I think your upload_image function could return a Promise.

Then you can call again the upload_image function if the promise is fulfilled

class BodyContent extends Component {

  componentDidMount() {
   const { actions } = this.props

   function call_upload_image_continiously() {
       actions.upload_image().then(call_upload_image_continiously);
   }

   call_upload_image_continiously();
}

Upvotes: 1

David Gilbertson
David Gilbertson

Reputation: 4863

You can just get your upload_image function to call itself. Note that you wouldn't actually have a setTimeout.

var actions = {
    uploadImage() {
        setTimeout(() => {
            console.log('Image has uploaded! Will go again now.');
            actions.uploadImage();
        }, 1000); // setTimeout just to simulate ansynchronousness
    }
}

actions.uploadImage();

jsbin: https://jsbin.com/hefaqu/1/edit?js,console

Upvotes: 0

Related Questions