From 0c3fb5b8d81af76de89c3a5a7ec877f8f7f85f1b Mon Sep 17 00:00:00 2001
From: Bastien DUMONT <bdumont@grandlyon.com>
Date: Mon, 2 Sep 2024 08:23:17 +0000
Subject: [PATCH] chore: harmonize useEffect usage

---
 .../Action/ActionList/ActionList.tsx          |  6 ++--
 .../Analysis/Comparison/Comparison.tsx        | 34 +++++++++----------
 .../ElecHalfHourMonthlyAnalysis.tsx           | 17 ++++------
 .../MaxConsumptionCard/MaxConsumptionCard.tsx |  5 ++-
 src/components/Analysis/MonthlyAnalysis.tsx   |  4 +--
 .../ProfileComparator/ProfileComparator.tsx   | 13 ++++---
 .../TotalAnalysisChart/TotalAnalysisChart.tsx |  4 +--
 .../ChallengeCardOnGoing.tsx                  | 12 +++----
 .../Consumption/ConsumptionView.tsx           |  2 +-
 .../EstimatedConsumptionModal.tsx             |  4 +--
 .../Duel/DuelOngoing/DuelOngoing.tsx          |  6 ++--
 .../Ecogesture/SingleEcogestureView.tsx       | 30 ++++++++--------
 .../EquipmentIcon/EquipmentIcon.tsx           |  4 +--
 .../EcogestureSelectionDetail.tsx             |  6 ++--
 .../EcogestureSelectionView.tsx               | 25 +++++++-------
 src/components/FluidChart/FluidChartSlide.tsx |  6 ++--
 .../Options/ExportData/ExportData.tsx         |  5 ++-
 .../Options/ReportOptions/ReportOptions.tsx   |  5 ++-
 .../Quiz/QuizQuestion/QuizQuestion.tsx        |  6 ++--
 .../TotalConsumption/TotalConsumption.tsx     |  6 ++--
 20 files changed, 86 insertions(+), 114 deletions(-)

diff --git a/src/components/Action/ActionList/ActionList.tsx b/src/components/Action/ActionList/ActionList.tsx
index 4de937d4c..c2bcdf72c 100644
--- a/src/components/Action/ActionList/ActionList.tsx
+++ b/src/components/Action/ActionList/ActionList.tsx
@@ -29,11 +29,9 @@ const ActionList = ({ setSelectedAction, setShowList }: ActionListProps) => {
       } else {
         actionList = await actionService.getDefaultActions()
       }
-      if (subscribed) {
-        setActions(actionList)
-      }
+      setActions(actionList)
     }
-    getActions()
+    subscribed && getActions()
     return () => {
       subscribed = false
     }
diff --git a/src/components/Analysis/Comparison/Comparison.tsx b/src/components/Analysis/Comparison/Comparison.tsx
index c21697f59..5aec14697 100644
--- a/src/components/Analysis/Comparison/Comparison.tsx
+++ b/src/components/Analysis/Comparison/Comparison.tsx
@@ -60,29 +60,27 @@ const Comparison = ({
   useEffect(() => {
     let subscribed = true
     async function populateData() {
-      if (subscribed) {
-        const fetchedYearIndicators =
-          await consumptionService.getPerformanceIndicators(
-            periods.monthPeriod,
-            TimeStep.MONTH,
-            fluidsWithData,
-            periods.previousYearPeriod
+      const fetchedYearIndicators =
+        await consumptionService.getPerformanceIndicators(
+          periods.monthPeriod,
+          TimeStep.MONTH,
+          fluidsWithData,
+          periods.previousYearPeriod
+        )
+      if (fetchedYearIndicators) {
+        setYearPerformanceIndicators(fetchedYearIndicators)
+        if (
+          fetchedYearIndicators.some(
+            indicator => indicator.value !== 0 || indicator.compareValue !== 0
           )
-        if (fetchedYearIndicators) {
-          setYearPerformanceIndicators(fetchedYearIndicators)
-          if (
-            fetchedYearIndicators.some(
-              indicator => indicator.value !== 0 || indicator.compareValue !== 0
-            )
-          ) {
-            dispatch(setPeriod('year'))
-          }
+        ) {
+          dispatch(setPeriod('year'))
         }
-        setIsLoading(false)
       }
+      setIsLoading(false)
     }
 
-    populateData()
+    subscribed && populateData()
     return () => {
       subscribed = false
     }
diff --git a/src/components/Analysis/ElecHalfHourMonthlyAnalysis/ElecHalfHourMonthlyAnalysis.tsx b/src/components/Analysis/ElecHalfHourMonthlyAnalysis/ElecHalfHourMonthlyAnalysis.tsx
index 9d4ede330..a7e0b78cc 100644
--- a/src/components/Analysis/ElecHalfHourMonthlyAnalysis/ElecHalfHourMonthlyAnalysis.tsx
+++ b/src/components/Analysis/ElecHalfHourMonthlyAnalysis/ElecHalfHourMonthlyAnalysis.tsx
@@ -86,7 +86,6 @@ const ElecHalfHourMonthlyAnalysis = ({
         FluidType.ELECTRICITY,
         TimeStep.HALF_AN_HOUR
       )
-      if (!subscribed) return
       if (isHalfHourLoadActivated) {
         setIsHalfHourActivated(true)
         const aggregatedDate = analysisMonth.minus({ month: 1 })
@@ -107,7 +106,7 @@ const ElecHalfHourMonthlyAnalysis = ({
 
       setIsLoading(false)
     }
-    fetchEnedisAnalysisData()
+    subscribed && fetchEnedisAnalysisData()
 
     return () => {
       subscribed = false
@@ -122,11 +121,11 @@ const ElecHalfHourMonthlyAnalysis = ({
         FluidType.ELECTRICITY,
         analysisMonth.minus({ month: 1 })
       )
-      if (subscribed && price) {
+      if (price) {
         setElecPrice(price)
       }
     }
-    getAllLastPrices()
+    subscribed && getAllLastPrices()
 
     return () => {
       subscribed = false
@@ -136,14 +135,12 @@ const ElecHalfHourMonthlyAnalysis = ({
   useEffect(() => {
     let subscribed = true
     async function getOffPeakHours() {
-      if (subscribed) {
-        const offPeakHours = await emas.getOffPeakHours()
-        if (offPeakHours) {
-          setOffPeakHours(offPeakHours)
-        }
+      const offPeakHours = await emas.getOffPeakHours()
+      if (offPeakHours) {
+        setOffPeakHours(offPeakHours)
       }
     }
-    getOffPeakHours()
+    subscribed && getOffPeakHours()
 
     return () => {
       subscribed = false
diff --git a/src/components/Analysis/MaxConsumptionCard/MaxConsumptionCard.tsx b/src/components/Analysis/MaxConsumptionCard/MaxConsumptionCard.tsx
index bfbc200d3..cf0c5d421 100644
--- a/src/components/Analysis/MaxConsumptionCard/MaxConsumptionCard.tsx
+++ b/src/components/Analysis/MaxConsumptionCard/MaxConsumptionCard.tsx
@@ -79,9 +79,8 @@ const MaxConsumptionCard = ({
       }
       setIsLoading(false)
     }
-    if (subscribed) {
-      getMaxLoadData()
-    }
+    subscribed && getMaxLoadData()
+
     return () => {
       subscribed = false
     }
diff --git a/src/components/Analysis/MonthlyAnalysis.tsx b/src/components/Analysis/MonthlyAnalysis.tsx
index 0b36bc41b..588b3bfff 100644
--- a/src/components/Analysis/MonthlyAnalysis.tsx
+++ b/src/components/Analysis/MonthlyAnalysis.tsx
@@ -111,9 +111,7 @@ const MonthlyAnalysis = ({
       setLoadingAnalysis(false)
     }
 
-    if (subscribed) {
-      populateData()
-    }
+    subscribed && populateData()
 
     return () => {
       saveLastScrollPosition()
diff --git a/src/components/Analysis/ProfileComparator/ProfileComparator.tsx b/src/components/Analysis/ProfileComparator/ProfileComparator.tsx
index aced331fa..162879be9 100644
--- a/src/components/Analysis/ProfileComparator/ProfileComparator.tsx
+++ b/src/components/Analysis/ProfileComparator/ProfileComparator.tsx
@@ -106,16 +106,15 @@ const ProfileComparator = ({
           analysisDate.year,
           analysisDate.month
         )
-        if (subscribed) {
-          setForecast(monthlyForecast)
-          if (monthlyForecast) {
-            getTotalValueWithConnectedFluids(monthlyForecast)
-          }
-          setIsLoading(false)
+
+        setForecast(monthlyForecast)
+        if (monthlyForecast) {
+          getTotalValueWithConnectedFluids(monthlyForecast)
         }
+        setIsLoading(false)
       }
     }
-    loadAverageConsumption()
+    subscribed && loadAverageConsumption()
     return () => {
       subscribed = false
     }
diff --git a/src/components/Analysis/TotalAnalysisChart/TotalAnalysisChart.tsx b/src/components/Analysis/TotalAnalysisChart/TotalAnalysisChart.tsx
index 806862bd4..3ec01cb5f 100644
--- a/src/components/Analysis/TotalAnalysisChart/TotalAnalysisChart.tsx
+++ b/src/components/Analysis/TotalAnalysisChart/TotalAnalysisChart.tsx
@@ -53,9 +53,7 @@ const TotalAnalysisChart = ({
       }
       setIsLoading(false)
     }
-    if (subscribed) {
-      getTotalData()
-    }
+    subscribed && getTotalData()
     return () => {
       subscribed = false
     }
diff --git a/src/components/Challenge/ChallengeCardOnGoing/ChallengeCardOnGoing.tsx b/src/components/Challenge/ChallengeCardOnGoing/ChallengeCardOnGoing.tsx
index 0caf08f96..b1ea160cc 100644
--- a/src/components/Challenge/ChallengeCardOnGoing/ChallengeCardOnGoing.tsx
+++ b/src/components/Challenge/ChallengeCardOnGoing/ChallengeCardOnGoing.tsx
@@ -103,12 +103,10 @@ const ChallengeCardOnGoing = ({
     let subscribed = true
     async function importIcon() {
       importIconById(userChallenge.id, 'challenge').then(icon => {
-        if (subscribed) {
-          icon ? setChallengeIcon(icon) : setChallengeIcon(defaultChallengeIcon)
-        }
+        icon ? setChallengeIcon(icon) : setChallengeIcon(defaultChallengeIcon)
       })
     }
-    importIcon()
+    subscribed && importIcon()
     return () => {
       subscribed = false
     }
@@ -121,9 +119,7 @@ const ChallengeCardOnGoing = ({
         userChallenge,
         currentDataload
       )
-      if (subscribed) {
-        setIsDone(isChallengeDone.isDone)
-      }
+      setIsDone(isChallengeDone.isDone)
     }
     const unlockDuel = async () => {
       if (
@@ -147,7 +143,7 @@ const ChallengeCardOnGoing = ({
       }
     }
     unlockDuel()
-    setChallengeResult()
+    subscribed && setChallengeResult()
     return () => {
       subscribed = false
     }
diff --git a/src/components/Consumption/ConsumptionView.tsx b/src/components/Consumption/ConsumptionView.tsx
index a4f19def0..213b656bb 100644
--- a/src/components/Consumption/ConsumptionView.tsx
+++ b/src/components/Consumption/ConsumptionView.tsx
@@ -142,7 +142,7 @@ const ConsumptionView = ({ fluidType }: { fluidType: FluidType }) => {
       }
     }
 
-    if (subscribed) setConsentExpiredFluids(expiredConsents)
+    subscribed && setConsentExpiredFluids(expiredConsents)
     return () => {
       subscribed = false
     }
diff --git a/src/components/ConsumptionVisualizer/EstimatedConsumptionModal.tsx b/src/components/ConsumptionVisualizer/EstimatedConsumptionModal.tsx
index faed95db0..8a985579d 100644
--- a/src/components/ConsumptionVisualizer/EstimatedConsumptionModal.tsx
+++ b/src/components/ConsumptionVisualizer/EstimatedConsumptionModal.tsx
@@ -29,11 +29,11 @@ const EstimatedConsumptionModal = ({
     const fluidsPricesService = new FluidPricesService(client)
     async function getAllLastPrices() {
       const prices = await fluidsPricesService.getAllLastPrices()
-      if (subscribed && prices) {
+      if (prices) {
         setPrices(prices)
       }
     }
-    getAllLastPrices()
+    subscribed && getAllLastPrices()
     return () => {
       subscribed = false
     }
diff --git a/src/components/Duel/DuelOngoing/DuelOngoing.tsx b/src/components/Duel/DuelOngoing/DuelOngoing.tsx
index 54cfc11db..cb9be0db1 100644
--- a/src/components/Duel/DuelOngoing/DuelOngoing.tsx
+++ b/src/components/Duel/DuelOngoing/DuelOngoing.tsx
@@ -85,12 +85,10 @@ const DuelOngoing = ({ userChallenge, isFinished }: DuelOngoingProps) => {
       if (isFinished) {
         const dataloads =
           await challengeService.getUserChallengeDataload(userChallenge)
-        if (subscribed) {
-          setFinishedDataLoad(dataloads)
-        }
+        setFinishedDataLoad(dataloads)
       }
     }
-    populateData()
+    subscribed && populateData()
     return () => {
       subscribed = false
     }
diff --git a/src/components/Ecogesture/SingleEcogestureView.tsx b/src/components/Ecogesture/SingleEcogestureView.tsx
index 077faf8d5..96bb2cc6a 100644
--- a/src/components/Ecogesture/SingleEcogestureView.tsx
+++ b/src/components/Ecogesture/SingleEcogestureView.tsx
@@ -71,25 +71,23 @@ const SingleEcogestureView = () => {
       const data = await ecogestureService.getEcogesturesByIds([
         ecogestureID || '',
       ])
-      if (subscribed) {
-        if (data?.[0]) {
-          setEcogesture(data[0])
-          // Prevent case this key doesn't exist in doctype
-          const icon = await importIconById(data[0].id, 'ecogesture')
-          if (subscribed) {
-            setEcogestureIcon(icon || defaultIcon)
-            if (currentChallenge?.exploration.ecogesture_id === data[0]._id) {
-              setValidExploration(currentChallenge.exploration.id)
-            }
-          }
-        } else {
-          logApp.error(`Could not find ecogesture ${ecogestureID}`)
-          Sentry.captureException(new Error('Could not find ecogesture'))
+
+      if (data?.[0]) {
+        setEcogesture(data[0])
+        // Prevent case this key doesn't exist in doctype
+        const icon = await importIconById(data[0].id, 'ecogesture')
+
+        setEcogestureIcon(icon || defaultIcon)
+        if (currentChallenge?.exploration.ecogesture_id === data[0]._id) {
+          setValidExploration(currentChallenge.exploration.id)
         }
-        setIsLoading(false)
+      } else {
+        logApp.error(`Could not find ecogesture ${ecogestureID}`)
+        Sentry.captureException(new Error('Could not find ecogesture'))
       }
+      setIsLoading(false)
     }
-    getSingleEcogesture()
+    subscribed && getSingleEcogesture()
 
     return () => {
       subscribed = false
diff --git a/src/components/EcogestureForm/EquipmentIcon/EquipmentIcon.tsx b/src/components/EcogestureForm/EquipmentIcon/EquipmentIcon.tsx
index 332a18824..c89d39d4f 100644
--- a/src/components/EcogestureForm/EquipmentIcon/EquipmentIcon.tsx
+++ b/src/components/EcogestureForm/EquipmentIcon/EquipmentIcon.tsx
@@ -16,11 +16,11 @@ const EquipmentIcon = ({ equipment, isChecked }: EquipmentIconProps) => {
     let subscribed = true
     async function getIcon() {
       const svg = await importIconById(equipment, 'equipments')
-      if (subscribed && svg) {
+      if (svg) {
         setIcon(svg)
       }
     }
-    getIcon()
+    subscribed && getIcon()
     return () => {
       subscribed = false
     }
diff --git a/src/components/EcogestureSelection/EcogestureSelectionDetail/EcogestureSelectionDetail.tsx b/src/components/EcogestureSelection/EcogestureSelectionDetail/EcogestureSelectionDetail.tsx
index 139480c97..40fab857b 100644
--- a/src/components/EcogestureSelection/EcogestureSelectionDetail/EcogestureSelectionDetail.tsx
+++ b/src/components/EcogestureSelection/EcogestureSelectionDetail/EcogestureSelectionDetail.tsx
@@ -30,11 +30,9 @@ const EcogestureSelectionDetail = ({
     let subscribed = true
     async function getIcon() {
       const icon = await importIconById(ecogesture.id, 'ecogesture')
-      if (subscribed) {
-        setEcogestureIcon(icon || defaultIcon)
-      }
+      setEcogestureIcon(icon || defaultIcon)
     }
-    getIcon()
+    subscribed && getIcon()
     setShowDetails(false)
     return () => {
       subscribed = false
diff --git a/src/components/EcogestureSelection/EcogestureSelectionView.tsx b/src/components/EcogestureSelection/EcogestureSelectionView.tsx
index df6806976..2ed05f844 100644
--- a/src/components/EcogestureSelection/EcogestureSelectionView.tsx
+++ b/src/components/EcogestureSelection/EcogestureSelectionView.tsx
@@ -94,22 +94,21 @@ const EcogestureSelectionView = () => {
         ecogesture => ecogesture.viewedInSelection === false
       )
       const slicedFilteredList = filteredList.slice(0, 10)
-      if (subscribed) {
-        if (
-          availableList.length === slicedFilteredList.length &&
-          slicedFilteredList.length > 0
-        ) {
-          setOpenEcSelectionModal(true)
-        }
-        setTotalAvailable(availableList.length)
-        setTotalViewed(availableList.length - filteredList.length)
-        setEcogestureList(slicedFilteredList)
-        setIndexEcogesture(0)
-        setIsLoading(false)
+
+      if (
+        availableList.length === slicedFilteredList.length &&
+        slicedFilteredList.length > 0
+      ) {
+        setOpenEcSelectionModal(true)
       }
+      setTotalAvailable(availableList.length)
+      setTotalViewed(availableList.length - filteredList.length)
+      setEcogestureList(slicedFilteredList)
+      setIndexEcogesture(0)
+      setIsLoading(false)
     }
 
-    getFilteredList()
+    subscribed && getFilteredList()
     return () => {
       subscribed = false
     }
diff --git a/src/components/FluidChart/FluidChartSlide.tsx b/src/components/FluidChart/FluidChartSlide.tsx
index a734dc266..3a20b9dc6 100644
--- a/src/components/FluidChart/FluidChartSlide.tsx
+++ b/src/components/FluidChart/FluidChartSlide.tsx
@@ -47,7 +47,7 @@ const FluidChartSlide = ({
   useEffect(() => {
     let subscribed = true
     async function loadData() {
-      if (currentTimeStep != timeStep && subscribed) {
+      if (currentTimeStep != timeStep) {
         setIsDataLoaded(false)
         setTimeStep(currentTimeStep)
       }
@@ -83,13 +83,13 @@ const FluidChartSlide = ({
           compareTimePeriod,
           isHome: isMulti,
         })
-        if (subscribed && graphData && graphData?.actualData.length > 0) {
+        if (graphData && graphData?.actualData.length > 0) {
           setChartData(graphData)
           setIsDataLoaded(true)
         }
       }
     }
-    loadData()
+    subscribed && loadData()
     return () => {
       subscribed = false
     }
diff --git a/src/components/Options/ExportData/ExportData.tsx b/src/components/Options/ExportData/ExportData.tsx
index 488dc64b9..51c761c79 100644
--- a/src/components/Options/ExportData/ExportData.tsx
+++ b/src/components/Options/ExportData/ExportData.tsx
@@ -56,9 +56,8 @@ const ExportData = () => {
       subscribed = false
     }
 
-    if (subscribed) {
-      getExportableFluids()
-    }
+    subscribed && getExportableFluids()
+
     return () => {
       subscribed = false
     }
diff --git a/src/components/Options/ReportOptions/ReportOptions.tsx b/src/components/Options/ReportOptions/ReportOptions.tsx
index 112aa1f30..bb0d8a6cb 100644
--- a/src/components/Options/ReportOptions/ReportOptions.tsx
+++ b/src/components/Options/ReportOptions/ReportOptions.tsx
@@ -79,9 +79,8 @@ const ReportOptions = () => {
         setLastSemesterMaxDay(lastSemesterMax as Dataload)
       }
     }
-    if (subscribed) {
-      getMaxLoadData()
-    }
+    subscribed && getMaxLoadData()
+
     return () => {
       subscribed = false
     }
diff --git a/src/components/Quiz/QuizQuestion/QuizQuestion.tsx b/src/components/Quiz/QuizQuestion/QuizQuestion.tsx
index 5e8b2fbca..8702fd98a 100644
--- a/src/components/Quiz/QuizQuestion/QuizQuestion.tsx
+++ b/src/components/Quiz/QuizQuestion/QuizQuestion.tsx
@@ -32,11 +32,9 @@ const QuizQuestion = ({ userChallenge }: { userChallenge: UserChallenge }) => {
         userChallenge.quiz.customQuestion,
         fluidTypes
       )
-      if (subscribed) {
-        setCustomQuestion(customQuestion)
-      }
+      setCustomQuestion(customQuestion)
     }
-    if (isCustomQuest) {
+    if (isCustomQuest && subscribed) {
       loadCustomQuestion()
     }
     return () => {
diff --git a/src/components/TotalConsumption/TotalConsumption.tsx b/src/components/TotalConsumption/TotalConsumption.tsx
index eec9e9ab7..75959c1e9 100644
--- a/src/components/TotalConsumption/TotalConsumption.tsx
+++ b/src/components/TotalConsumption/TotalConsumption.tsx
@@ -72,7 +72,7 @@ const TotalConsumption = ({ fluidType }: { fluidType: FluidType }) => {
   )
 
   useEffect(() => {
-    let isMounted = true
+    let subscribed = true
     const fetchTotal = async () => {
       await computeTotal(currentDatachart.actualData, setTotalValue)
       if (currentDatachart.comparisonData) {
@@ -82,9 +82,9 @@ const TotalConsumption = ({ fluidType }: { fluidType: FluidType }) => {
         )
       }
     }
-    isMounted && fetchTotal()
+    subscribed && fetchTotal()
     return () => {
-      isMounted = false
+      subscribed = false
     }
   }, [currentDatachart, fluidType, currentTimeStep, client, computeTotal])
 
-- 
GitLab