Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable ESlint rules for React Hooks #6651

Merged
merged 20 commits into from
May 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions web/.eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
"plugin:jsx-a11y/recommended",
"plugin:react/jsx-runtime",
"plugin:unicorn/recommended",
"plugin:react-hooks/recommended",
"plugin:react-prefer-function-component/recommended",
"prettier"
],
Expand Down
4 changes: 2 additions & 2 deletions web/src/api/getWeatherData.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { useQuery, UseQueryOptions } from '@tanstack/react-query';
import { add, startOfHour, sub } from 'date-fns';
import { useInterpolatedData } from 'features/weather-layers/hooks';
VIKTORVAV99 marked this conversation as resolved.
Show resolved Hide resolved
import { getInterpolatedData } from 'features/weather-layers/weatherUtils';
import type { Maybe } from 'types';

import { FIVE_MINUTES, getBasePath, getHeaders } from './helpers';
Expand Down Expand Up @@ -101,7 +101,7 @@ async function getWeatherData(type: WeatherType) {
const forecasts = await Promise.all([before, after]).then((values) => {
return values;
});
const interdata = useInterpolatedData(type, forecasts);
const interdata = getInterpolatedData(type, forecasts);
return interdata;
}

Expand Down
4 changes: 2 additions & 2 deletions web/src/api/getZone.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { useAtom } from 'jotai';
import invariant from 'tiny-invariant';
import type { ZoneDetails } from 'types';
import { TimeAverages } from 'utils/constants';
import { getZoneFromPath } from 'utils/helpers';
import { useGetZoneFromPath } from 'utils/helpers';
import { timeAverageAtom } from 'utils/state/atoms';

import { cacheBuster, getBasePath, getHeaders, QUERY_KEYS } from './helpers';
Expand Down Expand Up @@ -38,7 +38,7 @@ const getZone = async (
// TODO: The frontend (graphs) expects that the datetimes in state are the same as in zone
// should we add a check for this?
const useGetZone = (): UseQueryResult<ZoneDetails> => {
const zoneId = getZoneFromPath();
const zoneId = useGetZoneFromPath();
const [timeAverage] = useAtom(timeAverageAtom);
return useQuery<ZoneDetails>(
[QUERY_KEYS.ZONE, { zone: zoneId, aggregate: timeAverage }],
Expand Down
1 change: 1 addition & 0 deletions web/src/components/Accordion.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable react-hooks/rules-of-hooks */
import { PrimitiveAtom, useAtom } from 'jotai';
import { useEffect, useState } from 'react';
import { HiChevronDown, HiChevronUp } from 'react-icons/hi2';
Expand Down
2 changes: 1 addition & 1 deletion web/src/components/LoadingOverlay.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ function FadingOverlay({ isVisible }: { isVisible: boolean }) {
clearTimeout(timeoutId);
setShowButton(false);
};
}, [isVisible]);
}, [isVisible, showButton]);

return transitions(
(styles, isVisible) =>
Expand Down
4 changes: 2 additions & 2 deletions web/src/components/TimeSlider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { useDarkMode } from 'hooks/theme';
import { useAtom } from 'jotai/react';
import trackEvent from 'utils/analytics';
import { TimeAverages } from 'utils/constants';
import { getZoneFromPath } from 'utils/helpers';
import { useGetZoneFromPath } from 'utils/helpers';
import { timeAverageAtom } from 'utils/state/atoms';

type NightTimeSet = number[];
Expand Down Expand Up @@ -148,7 +148,7 @@ export function TimeSliderWithNight(props: TimeSliderProps) {
}

function TimeSlider(props: TimeSliderProps) {
const zoneId = getZoneFromPath();
const zoneId = useGetZoneFromPath();
const [timeAverage] = useAtom(timeAverageAtom);
const showNightTime = zoneId && timeAverage === TimeAverages.HOURLY;

Expand Down
3 changes: 2 additions & 1 deletion web/src/components/tooltips/TooltipWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,11 @@ export default function TooltipWrapper({
tooltipClassName,
isMobile,
}: TooltipWrapperProperties): ReactElement {
const [isOpen, setIsOpen] = useState(false);

if (!tooltipContent) {
return children;
}
const [isOpen, setIsOpen] = useState(false);

// Helpers
const openTooltip = () => setIsOpen(true);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { ElectricityModeType, ZoneDetail, ZoneKey } from 'types';
import { modeColor } from 'utils/constants';
import { formatCo2 } from 'utils/formatting';

import { LABEL_MAX_WIDTH, PADDING_X, PADDING_Y } from './constants';
import { LABEL_MAX_WIDTH, PADDING_X } from './constants';
import Axis from './elements/Axis';
import HorizontalBar from './elements/HorizontalBar';
import Row from './elements/Row';
Expand Down
31 changes: 13 additions & 18 deletions web/src/features/charts/elements/AreaGraph.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { TimeAverages } from 'utils/constants';
import { selectedDatetimeIndexAtom } from 'utils/state/atoms';
import { useBreakpoint } from 'utils/styling';

import { getTimeScale, isEmpty } from '../graphUtils';
import { getTimeScale } from '../graphUtils';
import AreaGraphTooltip from '../tooltips/AreaGraphTooltip';
import { AreaGraphElement, FillFunction, InnerAreaGraphTooltipProps } from '../types';
import AreaGraphLayers from './AreaGraphLayers';
Expand Down Expand Up @@ -140,26 +140,27 @@ function AreaGraph({
() => getValueScale(containerHeight, totalValues),
[containerHeight, totalValues]
);
const startTime = datetimes?.at(0);
const lastTime = datetimes?.at(-1);
const interval = datetimes?.at(-2);
const startTime = datetimes.at(0);
const lastTime = datetimes.at(-1);
const interval = datetimes.at(-2);

if (!startTime || !lastTime || !interval) {
return null;
}
VIKTORVAV99 marked this conversation as resolved.
Show resolved Hide resolved
const intervalMs =
datetimes.length > 1 && interval && lastTime
? lastTime.getTime() - interval.getTime()
: 0;
// The endTime needs to include the last interval so it can be shown
const endTime = useMemo(
() => new Date(lastTime.getTime() + intervalMs),
() => (lastTime ? new Date(lastTime.getTime() + intervalMs) : null),
[lastTime, intervalMs]
);
const datetimesWithNext = useMemo(() => [...datetimes, endTime], [datetimes, endTime]);
if (!endTime) {
return null;
}
VIKTORVAV99 marked this conversation as resolved.
Show resolved Hide resolved

const datetimesWithNext = useMemo(
// The as Date[] assertion is needed because the filter removes the null values but typescript can't infer that
// This can be inferred by typescript 5.5 and can be removed when we upgrade
() => [...datetimes, endTime].filter(Boolean) as Date[],
[datetimes, endTime]
);

const timeScale = useMemo(
() => getTimeScale(containerWidth, startTime, endTime),
[containerWidth, startTime, endTime]
Expand Down Expand Up @@ -209,12 +210,6 @@ function AreaGraph({
[setGraphIndex, setSelectedLayerIndex]
);

// Don't render the graph at all if no layers are present
if (isEmpty(layers)) {
console.error('No layers present in AreaGraph');
return null;
}

VIKTORVAV99 marked this conversation as resolved.
Show resolved Hide resolved
// Don't render the graph if datetimes and datapoints are not in sync
for (const layer of layers) {
if (layer.datapoints.length !== datetimes.length) {
Expand Down
17 changes: 10 additions & 7 deletions web/src/features/charts/graphUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,17 +44,20 @@ export const detectHoveredDatapointIndex = (
export const getTooltipPosition = (isMobile: boolean, marker: { x: number; y: number }) =>
isMobile ? { x: 0, y: 0 } : marker;

// TODO: Deprecate this
export const isEmpty = (object: any) =>
[Object, Array].includes((object || {}).constructor) &&
Object.entries(object || {}).length === 0;

VIKTORVAV99 marked this conversation as resolved.
Show resolved Hide resolved
export const noop = () => undefined;

export const getTimeScale = (width: number, startTime: Date, endTime: Date) =>
scaleTime()
export const getTimeScale = (
width: number,
startTime?: Date | null,
endTime?: Date | null
) => {
if (!startTime || !endTime) {
return null;
}
VIKTORVAV99 marked this conversation as resolved.
Show resolved Hide resolved
return scaleTime()
.domain([new Date(startTime), new Date(endTime)])
.range([0, width]);
};

export const getStorageKey = (name: ElectricityStorageType): string | undefined => {
switch (name) {
Expand Down
6 changes: 4 additions & 2 deletions web/src/features/charts/hooks/useNetExchangeChartData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,13 @@ export function getFills(data: AreaGraphElement[]) {

export function useNetExchangeChartData() {
const { data: zoneData, isLoading, isError } = useGetZone();
const [displayByEmissions] = useAtom(displayByEmissionsAtom);
const [timeAggregate] = useAtom(timeAverageAtom);

if (isLoading || isError) {
return { isLoading, isError };
}
const [displayByEmissions] = useAtom(displayByEmissionsAtom);
const [timeAggregate] = useAtom(timeAverageAtom);

const { valueFactor, valueAxisLabel } = getValuesInfo(
Object.values(zoneData.zoneStates),
displayByEmissions,
Expand Down
7 changes: 4 additions & 3 deletions web/src/features/charts/tooltips/NetExchangeChartTooltip.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,14 @@ import AreaGraphToolTipHeader from './AreaGraphTooltipHeader';
export default function NetExchangeChartTooltip({
zoneDetail,
}: InnerAreaGraphTooltipProps) {
if (!zoneDetail) {
return null;
}
const [timeAverage] = useAtom(timeAverageAtom);
const [displayByEmissions] = useAtom(displayByEmissionsAtom);
const { t } = useTranslation();

if (!zoneDetail) {
return null;
}

const isHourly = timeAverage === TimeAverages.HOURLY;
const { stateDatetime } = zoneDetail;

Expand Down
37 changes: 18 additions & 19 deletions web/src/features/exchanges/ExchangeArrow.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,15 +26,28 @@ function ExchangeArrow({
isMobile,
}: ExchangeArrowProps) {
const { co2intensity, lonlat, netFlow, rotation, key } = data;
if (!lonlat) {
return null;
}

const setIsMoving = useSetAtom(mapMovingAtom);

useEffect(() => {
const cancelWheel = (event: Event) => event.preventDefault();
const exchangeLayer = document.querySelector('#exchange-layer');
if (!exchangeLayer) {
return;
}
exchangeLayer.addEventListener('wheel', cancelWheel, {
passive: true,
});
return () => exchangeLayer.removeEventListener('wheel', cancelWheel);
}, []);

const absFlow = Math.abs(netFlow ?? 0);
// Don't render if the flow is very low ...
if (absFlow < 1) {

// Don't render if there is no position or if flow is very low ...
if (!lonlat || absFlow < 1) {
return null;
}

const mapZoom = map.getZoom();
const projection = map.project(lonlat);
const transform = {
Expand All @@ -56,20 +69,6 @@ function ExchangeArrow({
return null;
}

const setIsMoving = useSetAtom(mapMovingAtom);

useEffect(() => {
const cancelWheel = (event: Event) => event.preventDefault();
const exchangeLayer = document.querySelector('#exchange-layer');
if (!exchangeLayer) {
return;
}
exchangeLayer.addEventListener('wheel', cancelWheel, {
passive: true,
});
return () => exchangeLayer.removeEventListener('wheel', cancelWheel);
}, []);

const prefix = colorBlindMode ? 'colorblind-' : '';
const intensity = quantizedCo2IntensityScale(co2intensity);
const speed = quantizedExchangeSpeedScale(absFlow);
Expand Down
16 changes: 14 additions & 2 deletions web/src/features/map/Map.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,10 @@ export default function MapPage({ onMapLoad }: MapPageProps): ReactElement {
isSourceLoaded,
spatialAggregate,
isSuccess,
isLoading,
isError,
worldGeometries.features,
theme.clickableFill,
VIKTORVAV99 marked this conversation as resolved.
Show resolved Hide resolved
]);

useEffect(() => {
Expand All @@ -156,7 +160,7 @@ export default function MapPage({ onMapLoad }: MapPageProps): ReactElement {
map.flyTo({ center: [data.callerLocation[0], data.callerLocation[1]] });
setIsFirstLoad(false);
}
}, [map, isSuccess]);
}, [map, isSuccess, isError, isFirstLoad, data?.callerLocation, selectedZoneId]);

useEffect(() => {
// Run when the selected zone changes
Expand Down Expand Up @@ -186,7 +190,15 @@ export default function MapPage({ onMapLoad }: MapPageProps): ReactElement {
map.flyTo({ center: isMobile ? center : centerMinusLeftPanelWidth, zoom: 3.5 });
}
}
}, [map, location.pathname, isLoadingMap]);
}, [
map,
location.pathname,
isLoadingMap,
selectedZoneId,
setHoveredZone,
worldGeometries.features,
setLeftPanelOpen,
]);

const onClick = (event: maplibregl.MapLayerMouseEvent) => {
if (!map || !event.features) {
Expand Down
2 changes: 1 addition & 1 deletion web/src/features/map/MapWrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ export default function MapWrapper() {
if (shouldShowFallback) {
setIsLoadingMap(false);
}
}, [shouldShowFallback]);
}, [setIsLoadingMap, shouldShowFallback]);

return (
<>
Expand Down
Loading
Loading