Skip to content

Commit

Permalink
upcoming: [DI-22184] - Review changes: replaced watch with useWatch, …
Browse files Browse the repository at this point in the history
…removed non-null assertion and using default values while filtering form values, modified code to include just side effects in the useEffect in MetricCriteria component
  • Loading branch information
santoshp210-akamai committed Dec 16, 2024
1 parent 302095d commit b70b3a0
Show file tree
Hide file tree
Showing 5 changed files with 32 additions and 42 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { yupResolver } from '@hookform/resolvers/yup';
import { Paper, TextField, Typography } from '@linode/ui';
import { useSnackbar } from 'notistack';
import * as React from 'react';
import { Controller, FormProvider, useForm } from 'react-hook-form';
import { Controller, FormProvider, useForm, useWatch } from 'react-hook-form';
import { useHistory } from 'react-router-dom';

import { ActionsPanel } from 'src/components/ActionsPanel/ActionsPanel';
Expand Down Expand Up @@ -74,14 +74,7 @@ export const CreateAlertDefinition = () => {
),
});

const {
control,
formState,
getValues,
handleSubmit,
setError,
watch,
} = formMethods;
const { control, formState, getValues, handleSubmit, setError } = formMethods;
const { enqueueSnackbar } = useSnackbar();
const { mutateAsync: createAlert } = useCreateAlertDefinition(
getValues('serviceType')!
Expand All @@ -92,7 +85,7 @@ export const CreateAlertDefinition = () => {
*/
const [maxScrapeInterval, setMaxScrapeInterval] = React.useState<number>(0);

const serviceTypeWatcher = watch('serviceType');
const serviceTypeWatcher = useWatch({ control, name: 'serviceType' });
const onSubmit = handleSubmit(async (values) => {
try {
await createAlert(filterFormValues(values));
Expand Down Expand Up @@ -158,9 +151,9 @@ export const CreateAlertDefinition = () => {
{serviceTypeWatcher === 'dbaas' && <EngineOption name="engineType" />}
<CloudPulseRegionSelect name="region" />
<CloudPulseMultiResourceSelect
engine={watch('engineType')}
engine={useWatch({ control, name: 'engineType' })}
name="entity_ids"
region={watch('region')}
region={useWatch({ control, name: 'region' })}
serviceType={serviceTypeWatcher}
/>
<CloudPulseAlertSeveritySelect name="severity" />
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Autocomplete, Box } from '@linode/ui';
import { Stack, TextField, Typography } from '@linode/ui';
import { Grid } from '@mui/material';
import React from 'react';
import { Controller, useFormContext } from 'react-hook-form';
import { Controller, useFormContext, useWatch } from 'react-hook-form';

import {
MetricAggregationOptions,
Expand Down Expand Up @@ -46,11 +46,7 @@ interface MetricCriteriaProps {
export const Metric = (props: MetricCriteriaProps) => {
const { apiError, data, name, onMetricDelete, showDeleteIcon } = props;
const [isMetricDefinitionError, isMetricDefinitionLoading] = apiError;
const {
control,
setValue,
watch,
} = useFormContext<CreateAlertDefinitionForm>();
const { control, setValue } = useFormContext<CreateAlertDefinitionForm>();

const handleDataFieldChange = (
selected: { label: string; unit: MetricUnitType; value: string },
Expand Down Expand Up @@ -83,7 +79,7 @@ export const Metric = (props: MetricCriteriaProps) => {
: [];
}, [data]);

const metricWatcher = watch(`${name}.metric`);
const metricWatcher = useWatch({ control, name: `${name}.metric` });

const selectedMetric = React.useMemo(() => {
return data && metricWatcher
Expand All @@ -103,6 +99,7 @@ export const Metric = (props: MetricCriteriaProps) => {
: [];
}, [selectedMetric]);

const serviceWatcher = useWatch({ control, name: 'serviceType' });
return (
<Box
sx={(theme) => ({
Expand Down Expand Up @@ -154,7 +151,7 @@ export const Metric = (props: MetricCriteriaProps) => {
: null
}
data-testid={'Data-field'}
disabled={!watch('serviceType')}
disabled={!serviceWatcher}
label="Data Field"
loading={isMetricDefinitionLoading}
onBlur={field.onBlur}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Box, Button, Stack, Typography } from '@linode/ui';
import * as React from 'react';
import { useFieldArray, useFormContext } from 'react-hook-form';
import { useFieldArray, useFormContext, useWatch } from 'react-hook-form';

import { useGetCloudPulseMetricDefinitionsByServiceType } from 'src/queries/cloudpulse/services';

Expand Down Expand Up @@ -39,24 +39,24 @@ export const MetricCriteriaField = (props: MetricCriteriaProps) => {
serviceType !== null
);

const { control, watch } = useFormContext<CreateAlertDefinitionForm>();
const { control } = useFormContext<CreateAlertDefinitionForm>();

const metricCriteriaWatcher = watch(name);
React.useEffect(() => {
const formMetricValues = new Set(
metricCriteriaWatcher.map((item: MetricCriteriaForm) => item.metric)
);
const metricCriteriaWatcher = useWatch({ control, name });

const intervalList =
metricDefinitions?.data
.filter((item) =>
metricCriteriaWatcher.some(
(criteria: MetricCriteriaForm) => criteria.metric === item.metric
)
)
.map((item) => item.scrape_interval) || [];

const intervalList =
metricDefinitions &&
metricDefinitions.data
.filter((item) => formMetricValues.has(item.metric))
.map((item) => item.scrape_interval);
const maxInterval = Math.max(
...convertToSeconds(intervalList ? intervalList : [])
);
const maxInterval = Math.max(...convertToSeconds(intervalList));

React.useEffect(() => {
setMaxInterval(maxInterval);
}, [setMaxInterval, metricCriteriaWatcher, metricDefinitions]);
}, [maxInterval, setMaxInterval]);

const { append, fields, remove } = useFieldArray({
control,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ import { renderWithThemeAndHookFormContext } from 'src/utilities/testHelpers';

import { CloudPulseAlertSeveritySelect } from './AlertSeveritySelect';

describe('EngineOption component tests', () => {
it('should render the component when resource type is dbaas', () => {
describe('Severity component tests', () => {
it('should render the component', () => {
const { getByLabelText, getByTestId } = renderWithThemeAndHookFormContext({
component: <CloudPulseAlertSeveritySelect name={'severity'} />,
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export const filterFormValues = (
'rule_criteria',
]);
// severity has a need for null in the form for edge-cases, so null-checking and returning it as an appropriate type
const severity = formValues.severity!;
const severity = formValues.severity ?? 1;
const entityIds = formValues.entity_ids;
const rules = formValues.rule_criteria.rules;
return {
Expand All @@ -36,10 +36,10 @@ export const filterMetricCriteriaFormValues = (
const values = omitProps(rule, ['aggregation_type', 'operator', 'metric']);
return {
...values,
aggregation_type: rule.aggregation_type!,
aggregation_type: rule.aggregation_type ?? 'avg',
dimension_filters: rule.dimension_filters,
metric: rule.metric!,
operator: rule.operator!,
metric: rule.metric ?? '',
operator: rule.operator ?? 'eq',
};
});
};
Expand Down

0 comments on commit b70b3a0

Please sign in to comment.