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 6 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/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 { getBasePath, getHeaders, QUERY_KEYS } from './helpers';
Expand Down Expand Up @@ -36,7 +36,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
6 changes: 2 additions & 4 deletions web/src/components/Accordion.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,9 @@ export default function Accordion({
icon?: React.ReactNode;
children?: React.ReactNode;
title: string;
isCollapsedAtom?: PrimitiveAtom<boolean>;
isCollapsedAtom: PrimitiveAtom<boolean>;
}) {
const [collapsedAtom, setCollapsedAtom] = isCollapsedAtom
? useAtom(isCollapsedAtom)
: [null, null];
const [collapsedAtom, setCollapsedAtom] = useAtom(isCollapsedAtom);
const [isCollapsed, setIsCollapsed] = useState(isCollapsedDefault);

useEffect(() => {
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 @@ -4,7 +4,7 @@ import { useNightTimes } from 'hooks/nightTimes';
import { useDarkMode } from 'hooks/theme';
import { useAtom } from 'jotai/react';
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 @@ -137,7 +137,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
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
25 changes: 17 additions & 8 deletions web/src/features/panels/zone/EstimationCard.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,14 @@
import Accordion from 'components/Accordion';
import Badge from 'components/Badge';
import { useFeatureFlag } from 'features/feature-flags/api';
import { TFunction } from 'i18next';
Fixed Show fixed Hide fixed
import { useAtom } from 'jotai';
import { useEffect, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { ZoneDetails } from 'types';
import trackEvent from 'utils/analytics';
import {
estimationCardCollapsed,
feedbackCardCollapsedNumberAtom,
hasEstimationFeedbackBeenSeenAtom,
} from 'utils/state/atoms';
Expand All @@ -25,7 +27,7 @@
estimatedPercentage?: number;
outageMessage: ZoneDetails['zoneMessage'];
}) {
const [isFeedbackCardVisibile, setIsFeedbackCardVisibile] = useState(false);
const [isFeedbackCardVisible, setIsFeedbackCardVisibile] = useState(false);
const [feedbackCardCollapsedNumber, _] = useAtom(feedbackCardCollapsedNumberAtom);
const feedbackEnabled = useFeatureFlag('feedback-estimation-labels');
const [hasFeedbackCardBeenSeen, setHasFeedbackCardBeenSeen] = useAtom(
Expand All @@ -37,12 +39,18 @@
feedbackEnabled &&
showEstimationFeedbackCard(
feedbackCardCollapsedNumber,
isFeedbackCardVisibile,
isFeedbackCardVisible,
hasFeedbackCardBeenSeen,
setHasFeedbackCardBeenSeen
)
);
}, [feedbackEnabled, feedbackCardCollapsedNumber]);
}, [
feedbackEnabled,
feedbackCardCollapsedNumber,
isFeedbackCardVisible,
hasFeedbackCardBeenSeen,
setHasFeedbackCardBeenSeen,
]);

switch (cardType) {
case 'outage': {
Expand All @@ -55,14 +63,14 @@
return (
<div>
<EstimatedCard estimationMethod={estimationMethod} />
{isFeedbackCardVisibile && <FeedbackCard estimationMethod={estimationMethod} />}
{isFeedbackCardVisible && <FeedbackCard estimationMethod={estimationMethod} />}
</div>
);
}
}
}

function getEstimationTranslation(
function useGetEstimationTranslation(
field: 'title' | 'pill' | 'body',
estimationMethod?: string,
estimatedPercentage?: number
Expand Down Expand Up @@ -117,13 +125,13 @@
};
const { t } = useTranslation();

const title = getEstimationTranslation('title', estimationMethod);
const pillText = getEstimationTranslation(
const title = useGetEstimationTranslation('title', estimationMethod);
const pillText = useGetEstimationTranslation(
'pill',
estimationMethod,
estimatedPercentage
);
const bodyText = getEstimationTranslation(
const bodyText = useGetEstimationTranslation(
'body',
estimationMethod,
estimatedPercentage
Expand All @@ -150,6 +158,7 @@
className={textColorTitle}
icon={<div className={`h-[16px] w-[16px] bg-center ${icon}`} />}
title={title}
isCollapsedAtom={estimationCardCollapsed}
>
<div className="gap-2">
<div
Expand Down
25 changes: 13 additions & 12 deletions web/src/features/panels/zone/FeedbackCard.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as ToggleGroupPrimitive from '@radix-ui/react-toggle-group';
import Pill from 'components/Pill';
import { TFunction } from 'i18next';
Fixed Show fixed Hide fixed
import { ChangeEvent, Dispatch, SetStateAction, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { HiOutlineX } from 'react-icons/hi';
Expand All @@ -22,8 +23,8 @@
setIsClosed(true);
};

const title = getQuestionTranslation('title', feedbackState);
const subtitle = getQuestionTranslation('subtitle', feedbackState);
const title = useGetQuestionTranslation('title', feedbackState);
const subtitle = useGetQuestionTranslation('subtitle', feedbackState);

if (isClosed) {
return null;
Expand Down Expand Up @@ -81,9 +82,9 @@
inputText: string;
handleInputChange: (event: { target: { value: SetStateAction<string> } }) => void;
}) {
const inputPlaceholder = getQuestionTranslation('placeholder');
const optional = getQuestionTranslation('optional');
const text = getQuestionTranslation('input-question');
const inputPlaceholder = useGetQuestionTranslation('placeholder');
const optional = useGetQuestionTranslation('optional');
const text = useGetQuestionTranslation('input-question');

return (
<div>
Expand Down Expand Up @@ -114,7 +115,7 @@
}

function SubmitButton({ handleSave }: { handleSave: () => void }) {
const buttonText = getQuestionTranslation('submit');
const buttonText = useGetQuestionTranslation('submit');

return <Pill text={buttonText} onClick={handleSave} />;
}
Expand All @@ -129,9 +130,9 @@
estimationMethod?: string;
}) {
const [inputText, setInputText] = useState('');
const [feedbackScore, setfeedbackScore] = useState('');
const [feedbackScore, setFeedbackScore] = useState('');

const question = getQuestionTranslation('rate-question');
const question = useGetQuestionTranslation('rate-question');

const handleInputChange = (event: { target: { value: SetStateAction<string> } }) => {
setInputText(event.target.value);
Expand Down Expand Up @@ -160,7 +161,7 @@
</div>
<ActionPills
setFeedbackState={setFeedbackState}
setFeedbackScore={setfeedbackScore}
setFeedbackScore={setFeedbackScore}
/>
{feedbackState === FeedbackState.OPTIONAL && (
<div>
Expand All @@ -182,9 +183,9 @@
setFeedbackState: Dispatch<SetStateAction<FeedbackState>>;
setFeedbackScore: Dispatch<SetStateAction<string>>;
}) {
const agreeText = getQuestionTranslation('agree');
const agreeText = useGetQuestionTranslation('agree');
const [pillContent] = useState(['1', '2', '3', '4', '5']);
const disagreeText = getQuestionTranslation('disagree');
const disagreeText = useGetQuestionTranslation('disagree');
const [currentPillNumber, setPillNumber] = useState('');

const handlePillClick = (identifier: string) => {
Expand Down Expand Up @@ -257,7 +258,7 @@
);
}

function getQuestionTranslation(field: string, feedbackState?: FeedbackState) {
function useGetQuestionTranslation(field: string, feedbackState?: FeedbackState) {
const { t } = useTranslation();
if (feedbackState != undefined) {
if (
Expand Down
Loading
Loading