From 4f6a705c69b91f1004cd6cf71bc28683a7bdaa15 Mon Sep 17 00:00:00 2001
From: Julia Friesel <julia.friesel@gmail.com>
Date: Mon, 15 Oct 2018 14:41:44 +0200
Subject: [PATCH] Remove listeners on layout before re-adding them

---
 components/chart/chart.js | 37 +++++++++++++++++++++++++++----------
 1 file changed, 27 insertions(+), 10 deletions(-)

diff --git a/components/chart/chart.js b/components/chart/chart.js
index 14d03ce7..87c37172 100644
--- a/components/chart/chart.js
+++ b/components/chart/chart.js
@@ -48,9 +48,7 @@ export default class CycleChart extends Component {
   onLayout = ({ nativeEvent }) => {
     if (this.state.chartHeight) return
     const height = nativeEvent.layout.height
-    this.setState({ chartHeight: height })
-    this.reCalculateChartInfo = (_, changes) => {
-      if (nothingChanged(changes)) return
+    const reCalculateChartInfo = () => {
       // how many symptoms need to be displayed on the chart's upper symptom row?
       this.symptomRowSymptoms = [
         'bleeding',
@@ -66,8 +64,8 @@ export default class CycleChart extends Component {
         })
       })
 
-      this.xAxisHeight = this.state.chartHeight * config.xAxisHeightPercentage
-      const remainingHeight = this.state.chartHeight - this.xAxisHeight
+      this.xAxisHeight = height * config.xAxisHeightPercentage
+      const remainingHeight = height - this.xAxisHeight
       this.symptomHeight = config.symptomHeightPercentage * remainingHeight
       this.symptomRowHeight = this.symptomRowSymptoms.length *
         this.symptomHeight
@@ -78,16 +76,35 @@ export default class CycleChart extends Component {
         this.chartSymptoms.push('temperature')
       }
 
-      const columnData = this.makeColumnInfo()
-      this.setState({ columns: columnData })
+      const columnData = this.makeColumnInfo(nfpLines(), this.chartSymptoms)
+      this.setState({
+        columns: columnData,
+        chartHeight: height
+      })
+    }
+
+    reCalculateChartInfo()
+    this.updateListeners(reCalculateChartInfo)
+  }
+
+  updateListeners(dataUpdateHandler) {
+    // remove existing listeners
+    if(this.handleDbChange) {
+      this.cycleDaysSortedByDate.removeListener(this.handleDbChange)
+    }
+    if (this.removeObvListener) this.removeObvListener()
+
+    this.handleDbChange = (_, changes) => {
+      if (nothingChanged(changes)) return
+      dataUpdateHandler()
     }
 
-    this.cycleDaysSortedByDate.addListener(this.reCalculateChartInfo)
-    this.removeObvListener = scaleObservable(this.reCalculateChartInfo, false)
+    this.cycleDaysSortedByDate.addListener(this.handleDbChange)
+    this.removeObvListener = scaleObservable(dataUpdateHandler, false)
   }
 
   componentWillUnmount() {
-    this.cycleDaysSortedByDate.removeListener(this.reCalculateChartInfo)
+    this.cycleDaysSortedByDate.removeListener(this.handleDbChange)
     this.removeObvListener()
   }
 
-- 
GitLab