Skip to content

How can we fetch data async in reaction to props changes with getDerivedStateFromProps? #26

Closed
@felixfbecker

Description

@felixfbecker

I couldn't find this mentioned in the RFC.
Currently almost all of our components implement compoentWillReceiveProps to trigger some async operation in reaction to props changes, then call setState asynchronously. Simple example:

componentWillReceiveProps(newProps) {
  if (this.props.userID !== newProps.userID) {
    this.setState({ profileOrError: undefined })
    fetchUserProfile(newProps.userID)
      .catch(error => error)
      .then(profileOrError => this.setState({ profileOrError }))
  }
}

I.e. the new derived state from the Props is not derived synchronously, but asynchronously. Given that getDerivedStateFromProps is sync, I don't see how this could work with the new API.

Note that the above example is very simple, is prone to race conditions if the responses arrive out of order and does no cancellation on new values or component unmount.

We usually make use of RxJS Observables to solve all those issues:

private propsUpdates = new Subject<Props>()
private subscription: Subscription

componentDidMount() {
  this.subscription = this.propsUpdates
    .pipe(
      map(props => props.userID),
      distinctUntilChanged(),
      switchMap(userID => fetchUserProfile(userID).pipe(catchError(error => [error])))
    )
    .subscribe(profileOrError => {
      this.setState({ profileOrError })
    })
  this.propsUpdates.next(this.props)
}

componentWillReceiveProps(newProps) {
  this.propsUpdates.next(newProps)
}

componentDidUnmount() {
  this.subscription.unsubscribe()
}

So now that the methods we were making use of are deprecated, I wonder were we doing this wrong all the time? Is there already a better way to do this with the old API? And what is the recommended way to do this with the new API?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions