Test Failed
Pull Request — development (#86)
by Vad
10:46
created

ShowMap.tsx ➔ ShowMap   F

Complexity

Conditions 13

Size

Total Lines 94
Code Lines 78

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 23
CRAP Score 16.7577

Importance

Changes 0
Metric Value
eloc 78
dl 0
loc 94
rs 3.66
c 0
b 0
f 0
ccs 23
cts 32
cp 0.7188
cc 13
crap 16.7577

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like ShowMap.tsx ➔ ShowMap often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import Map from '../../components/Map';
2
import { useParams } from "react-router-dom";
3
import axios, { AxiosError } from 'axios';
4
import { API_URL} from '../../helpers/config';
5
import { useEffect, useState, useRef } from 'react';
6
import { Zone } from '../../helpers/map/leaflet-types'
7
import { Scooter } from '../../helpers/bike-functions';
8
import { Label, ToggleSwitch } from 'flowbite-react';
9
import AdminGate from '../../components/AdminGate';
10
11
import BikeList from '../../components/BikeList';
12
13
export default function ShowMap() {
14 1
    const { city }  = useParams();
15 1
    const [zoneData, setZoneData] = useState<Zone[]>([]);
16 1
    const [scooterData, setScooterData] = useState<Scooter[]>([]);
17 1
    const [realTime, setRealTime] = useState(false);
18 1
    const timerRef = useRef<null | number>(null);
19 1
    const [trigger, setTrigger] = useState(0);
20
  
21 1
    const updateRealTime = () => {
22
      setRealTime(!realTime);
23 2
      if (realTime)
24
      {
25
        stopTimer();
26
      } else {
27
        startTimer();
28
      }
29
      
30
    }
31
32 1
    const startTimer = () => {
33 2
      if (!timerRef.current)
34
        {
35
          timerRef.current = setInterval(() => {
36
            setTrigger((prev) => prev + 1);
37
          }, 1000);
38
        }
39
  };
40
41 1
  const stopTimer = () => {
42 2
      if (timerRef.current)
43
        {
44
          clearInterval(timerRef.current);
45
          timerRef.current = null;
46
        }
47
  };
48
    
49 1
    useEffect(() => {
50 1
      const fetchScooters = async() => {
51 1
      try {
52 1
              const response = await axios.get(`${API_URL}/bike/city/${city}`);
53
              setScooterData(response.data);
54
          }
55
          catch(error)
56
          {
57
            const axiosError = error as AxiosError;
58
            console.log(axiosError?.response?.data);
59 1
          }
60
    }
61
    fetchScooters();
62 1
    },[city, trigger])
63 1
64 1
    useEffect(() => {
65
      const fetchZones = async () => {
66 1
      try {
67
68
              const response = await axios.get(`${API_URL}/zone/city/${city}`);
69
              setZoneData(response.data);
70
          }
71
          catch(error)
72
          {
73 1
            const axiosError = error as AxiosError;
74
            console.log(axiosError?.response?.data);
75
          }
76
    }
77 1
    fetchZones();
78
    },[city, trigger])
79
80
81
  return (
82
    <>
83
    <AdminGate/>
84
      <div data-testid="show-map" className="mx-auto sm:max-w-4xl"><Map city={city ?? "Göteborg"} zoneData={zoneData} scooterData={scooterData}/></div>
85
      <div className="flex flex-col items-center justify-center my-2 py-2 bg-red-100 rounded-md w-full sm:max-w-xl mx-auto">
86
      <Label htmlFor="realtimetoggle">Vill du uppdatera kartan i realtid?</Label>
87
      <ToggleSwitch id="realtimetoggle" checked={realTime} onChange={updateRealTime}>Uppdatera i realtid?</ToggleSwitch>
88
      </div>
89
        <div id="scooter-list" className="p-4 flex flex-col justify-center w-full">
90
          <div className="mx-auto">
91
          <h2 className="text-4xl font-bold text-gray-900"> Cyklar i {city}: </h2>
92
        </div>
93
      {scooterData.length > 0 ? (
94
        <>
95
        <div className="mx-auto mb-5">
96
        <h2>Antal cyklar: <b>{scooterData.length}</b> </h2>
97
        </div>
98
        <BikeList scooterData={scooterData} isCityList={false}/>
99
        </>) : (
100
                <div className="mx-auto mb-5">
101
                    <p>Inga cyklar tillgängliga</p>
102
                </div>
103
    )}
104
    </div>
105
  </>
106
  )
107
};
108