Audun Olsen
Audun Olsen

Reputation: 638

React — componentDidUpdate as a promise/callback. Is it possible?

I have a class method I use to update a component's state. I want the method to return a promise which resolves when the component has updated. The method I intend to use for updating my components state will only be called during very specific circumstances, thus the conventional way of using componentDidUpdate will only make things extremely convoluted.

Some pseudo:

addItems(newItems) {

  this.setState({items: [...this.state.items, ...newItems]});

  return new Promise(resolve => {
    this.componentDidUpdate(() => resolve());
  });

}

Any suggestions?

Upvotes: 1

Views: 705

Answers (2)

Anirudha
Anirudha

Reputation: 32817

If you don't want to clutter componentDidUpdate, you can use the setState callback which gets called after state is updated and re-rendering. Obviously its recommended to have such logic in componentDidUpdate.

this.setState({items: [...this.state.items, ...newItems]},function(){
    //gets called after state update and re-rendering.
});

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1075317

You can have an unresolved promise that componentDidUpdate resolves and then replaces with a new one. Then, in addItems, you wait for the current update promise to resolve. One advantage of this is that if you have multiple places in the code that need to be notified when the update happens, they can all use the same promise. (You could also do it with an array of callbacks you add to and then componentDidUpdate notifies, but...that's basically what the promise does, and if it's a promise you can use the various promise composition patterns, etc., if needed.)

Add a method:

createUpdatePromise() {
    this.updatePromise = new Promise(resolve => {
        this.resolveUpdatePromise = resolve;
    });
}

Call it from your constructor.

Then, in componentDidUpdate:

this.resolveUpdatePromise();
this.createUpdatePromise();

addItems:

addItems(newItems) {
  this.setState({items: [...this.state.items, ...newItems]});

  this.updatePromise()
  .then(() => {
    // Updated
  });
}

Upvotes: 1

Related Questions