rallrall
rallrall

Reputation: 4770

Redux, callback after synchronous action

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?

Upvotes: 3

Views: 978

Answers (1)

gcedo
gcedo

Reputation: 4931

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

Upvotes: 6

Related Questions