Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redux, callback after synchronous action

Tags:

reactjs

redux

I'm trying to figure out how to properly implement a callback after a synchronous action is called, and the relevant react components has been updated. What I'm trying to do can be compared with scrolling to, and focusing a newly created todo.

What I'm currently doing:

// in Entries Component
createEntry() {
  this.props.actions.createNewEntry(key);

  setTimeout(() => {
    // accessing updated DOM
    this.scrollToAndFocus(key);
  });
}

It works, but it feels very brittle and hackish. There must be a better way?

like image 630
rallrall Avatar asked Nov 16 '25 05:11

rallrall


1 Answers

As answered in the comments, the right hook in the component lifecycle is componentDidUpdate. From the docs:

Invoked immediately after the component's updates are flushed to the DOM. This method is not called for the initial render.

Therefore your component becomes:

createEntry() {
    this.props.actions.createNewEntry(key);
}

componentDidUpdate() {
    this.scrollToAndFocus(key);
}

Be aware that if you further modify the DOM in componentDidUpdate, then you should implement a stop condition, otherwise you would end up in an endless loop. This can be done either

  • by overriding shouldComponentUpdate, if the stop condition depends on the current and future values of props or state.
  • in componentDidUpdate, if it depends on some DOM properties, e.g., document.activeElement
like image 123
gcedo Avatar answered Nov 18 '25 21:11

gcedo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!