1

I have a react component which uses the subscribeToMore method on an apollo graphql query to update itself on changes. It does that just fine, but I want to call some outside function when the subscription picks up a change. I want to show some hints in the UI that things have changed, let's call our function 'onUpdate', Where do I call this onUpdate function?

My component has some code that looks like this before the render function:

subscribeToNewPoints = () => {
  this.props.studentSessionPointsQuery.subscribeToMore({
    document: NEW_POINT_STUDENT_SESSION_SUBSCRIPTION,
    variables,
    updateQuery: (previous, { subscriptionData }) => {
      const newAllPoints = [
        subscriptionData.data.Point.node,
        ...previous.allPoints
      ]
      const result = {
        ...previous,
        allPoints: newAllPoints
      }
      return result
    }
  })
}

componentDidMount() {
    this.subscribeToNewPoints()
}

Am I supposed to put my onUpdate function inside here, or somewhere else?

Forgive me if this is answered in another question, but all the others I could find appeared to be asking how to update the cache for the query or how to get subscriptions to work in the first place.

James
  • 87
  • 1
  • 8

1 Answers1

0

React has it's lifecycle event ComponentWillUpdate which called right before your component gets an update. Or You can use ComponentDidUpdate which called just after your component gets an update.

ComponentWillUpdate() {
 /*called just before an update */
 onUpdateFunc()
}

ComponentDidUpdate() {
 /*called just after an update */
 onUpdateFunc()
}
Muneeb
  • 1,469
  • 16
  • 24
  • 1
    I think you may have misunderstood my question. I'm asking how I can call a function when my data gets updated, not when my component gets updated. Using ComponentDidUpdate() like this in my app the function gets triggered before any updates to the data occur. – James Dec 25 '17 at 02:35