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?
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
shouldComponentUpdate, if the stop condition depends on the current and future values of props or state.componentDidUpdate, if it depends on some DOM properties, e.g., document.activeElementIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With