Skip to content

Commit 372c9d4

Browse files
Alerting: Fix possible undefined value in the form not being protected (grafana#88860)
Fix possible undefined value in the form not being protected
1 parent a1851b4 commit 372c9d4

File tree

1 file changed

+13
-16
lines changed

1 file changed

+13
-16
lines changed

public/app/features/alerting/unified/components/receivers/form/fields/TemplateSelector.tsx

+13-16
Original file line numberDiff line numberDiff line change
@@ -163,14 +163,14 @@ function TemplateSelector({ onSelect, onClose, option, valueInForm }: TemplateSe
163163

164164
// if we are using only one template, we should settemplate to that template
165165
useEffect(() => {
166-
if (matchesOnlyOneTemplate(valueInForm)) {
167-
const name = getTemplateName(valueInForm);
168-
setTemplate({
169-
name,
170-
content: getContentFromOptions(name, options),
171-
});
172-
} else {
173-
if (Boolean(valueInForm)) {
166+
if (Boolean(valueInForm)) {
167+
if (matchesOnlyOneTemplate(valueInForm)) {
168+
const name = getTemplateName(valueInForm);
169+
setTemplate({
170+
name,
171+
content: getContentFromOptions(name, options),
172+
});
173+
} else {
174174
// if it's empty we default to select existing template
175175
setTemplateOption('Custom');
176176
}
@@ -303,20 +303,16 @@ export function WrapWithTemplateSelection({
303303
name,
304304
children,
305305
}: WrapWithTemplateSelectionProps) {
306-
const { getValues } = useFormContext();
307-
const value: string = getValues(name) ?? '';
308-
const emptyValue = value === '' || value === undefined;
309-
const onlyOneTemplate = value ? matchesOnlyOneTemplate(value) : false;
310306
const styles = useStyles2(getStyles);
311-
307+
const { getValues } = useFormContext();
308+
const value = getValues(name) ?? '';
312309
// if the placeholder does not contain a template, we don't need to show the template picker
313-
if (!option.placeholder.includes('{{ template ')) {
310+
if (!option.placeholder.includes('{{ template ') || typeof value !== 'string') {
314311
return <>{children}</>;
315312
}
316313
// Otherwise, we can use templates on this field
317-
318314
// if the value is empty, we only show the template picker
319-
if (emptyValue) {
315+
if (!value) {
320316
return (
321317
<div className={styles.inputContainer}>
322318
<Stack direction="row" gap={1} alignItems="center">
@@ -327,6 +323,7 @@ export function WrapWithTemplateSelection({
327323
</div>
328324
);
329325
}
326+
const onlyOneTemplate = value ? matchesOnlyOneTemplate(value) : false;
330327
if (onlyOneTemplate) {
331328
return (
332329
<div className={styles.inputContainer}>

0 commit comments

Comments
 (0)