From b9f504204442b6c84acb519ea0fe635352a546ed Mon Sep 17 00:00:00 2001 From: Joey <90795735+joey-grafana@users.noreply.github.com> Date: Wed, 31 Jan 2024 09:08:06 +0000 Subject: [PATCH] Tempo: Add query ref in the query editor (#81343) * Add query ref * Fix lint * Add comment * Update public/app/plugins/datasource/tempo/traceql/QueryEditor.tsx Co-authored-by: Fabrizio <135109076+fabrizio-grafana@users.noreply.github.com> --------- Co-authored-by: Fabrizio <135109076+fabrizio-grafana@users.noreply.github.com> --- .../plugins/datasource/tempo/traceql/QueryEditor.tsx | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/public/app/plugins/datasource/tempo/traceql/QueryEditor.tsx b/public/app/plugins/datasource/tempo/traceql/QueryEditor.tsx index 8dee357cef9..c4e9f977f22 100644 --- a/public/app/plugins/datasource/tempo/traceql/QueryEditor.tsx +++ b/public/app/plugins/datasource/tempo/traceql/QueryEditor.tsx @@ -1,6 +1,6 @@ import { css } from '@emotion/css'; import { defaults } from 'lodash'; -import React, { useState } from 'react'; +import React, { useRef, useState } from 'react'; import { QueryEditorProps } from '@grafana/data'; import { config, reportInteraction } from '@grafana/runtime'; @@ -27,8 +27,14 @@ export function QueryEditor(props: Props) { return genQuery === query.query || genQuery === '{}'; }); + // The Monaco Editor uses the first version of props.onChange in handleOnMount i.e. always has the initial + // value of query because underlying Monaco editor is passed `query` below in the onEditorChange callback. + // handleOnMount is called only once when the editor is mounted and does not get updates to query. + // So we need useRef to get the latest version of query in the onEditorChange callback. + const queryRef = useRef(query); + queryRef.current = query; const onEditorChange = (value: string) => { - props.onChange({ ...query, query: value }); + props.onChange({ ...queryRef.current, query: value }); }; return (