From 372c9d46d5a2935556123d3e51576f66e4d84139 Mon Sep 17 00:00:00 2001 From: Sonia Aguilar <33540275+soniaAguilarPeiron@users.noreply.github.com> Date: Fri, 7 Jun 2024 12:29:09 +0200 Subject: [PATCH] Alerting: Fix possible undefined value in the form not being protected (#88860) Fix possible undefined value in the form not being protected --- .../form/fields/TemplateSelector.tsx | 29 +++++++++---------- 1 file changed, 13 insertions(+), 16 deletions(-) diff --git a/public/app/features/alerting/unified/components/receivers/form/fields/TemplateSelector.tsx b/public/app/features/alerting/unified/components/receivers/form/fields/TemplateSelector.tsx index 6c62c30fbe7..4a571eb6f71 100644 --- a/public/app/features/alerting/unified/components/receivers/form/fields/TemplateSelector.tsx +++ b/public/app/features/alerting/unified/components/receivers/form/fields/TemplateSelector.tsx @@ -163,14 +163,14 @@ function TemplateSelector({ onSelect, onClose, option, valueInForm }: TemplateSe // if we are using only one template, we should settemplate to that template useEffect(() => { - if (matchesOnlyOneTemplate(valueInForm)) { - const name = getTemplateName(valueInForm); - setTemplate({ - name, - content: getContentFromOptions(name, options), - }); - } else { - if (Boolean(valueInForm)) { + if (Boolean(valueInForm)) { + if (matchesOnlyOneTemplate(valueInForm)) { + const name = getTemplateName(valueInForm); + setTemplate({ + name, + content: getContentFromOptions(name, options), + }); + } else { // if it's empty we default to select existing template setTemplateOption('Custom'); } @@ -303,20 +303,16 @@ export function WrapWithTemplateSelection({ name, children, }: WrapWithTemplateSelectionProps) { - const { getValues } = useFormContext(); - const value: string = getValues(name) ?? ''; - const emptyValue = value === '' || value === undefined; - const onlyOneTemplate = value ? matchesOnlyOneTemplate(value) : false; const styles = useStyles2(getStyles); - + const { getValues } = useFormContext(); + const value = getValues(name) ?? ''; // if the placeholder does not contain a template, we don't need to show the template picker - if (!option.placeholder.includes('{{ template ')) { + if (!option.placeholder.includes('{{ template ') || typeof value !== 'string') { return <>{children}>; } // Otherwise, we can use templates on this field - // if the value is empty, we only show the template picker - if (emptyValue) { + if (!value) { return (