Keep two values in sync when data changes

159 views Asked by At

I have two variables goalsData and goals which work correctly on initial load but I would like to keep goal in sync with goalsData so that if there is a change on goalsData that change persists to goals how might I achieve this?

ngOnInit() {
    this.goalsData = this.apollo.watchQuery({ query: GoalQuery, forceFetch: true });
    this.goals = this.goalsData.map(({data}) => data.allGoals);

    console.log(this.goals);
  }
1

There are 1 answers

0
Reactgular On

I haven't used Apollo, but the watchQuery is returning an Observable. Which means that you have to subscribe to it to get the changes.

ngOnInit() {
     this.goalsData = this.apollo.watchQuery({ query: GoalQuery, forceFetch: true });
     this.goalsData
         .map({data}=>data.allGoals)
         .subscribe((goals)=>{
             this.goals = goals;
             console.log(this.goals);
         },(err)=>{
             console.error(err);
         },()=>{
             console.log('finished');
         });
}

Assuming apollo will be emitting goal data this will keep updating this.goals