Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

chore: dashboard grid / widget / hooks to use new variable store (#10147)

Ashwin Bhatkal424127c27c64
diff --git a/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx b/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx
index 7ec845005c..0c414ac298 100644
--- a/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx
+++ b/frontend/src/container/GridCardLayout/GridCard/FullView/index.tsx
@@ -25,6 +25,7 @@ import {
} from 'container/NewWidget/RightContainer/timeItems';
import PanelWrapper from 'container/PanelWrapper/PanelWrapper';
import RightToolbarActions from 'container/QueryBuilder/components/ToolbarActions/RightToolbarActions';
+import { useDashboardVariables } from 'hooks/dashboard/useDashboardVariables';
import { useGetQueryRange } from 'hooks/queryBuilder/useGetQueryRange';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import { useChartMutable } from 'hooks/useChartMutable';
@@ -79,6 +80,7 @@ function FullView({
}, [setCurrentGraphRef]);
const { selectedDashboard, isDashboardLocked } = useDashboard();
+ const { dashboardVariables } = useDashboardVariables();
const { user } = useAppContext();
const [editWidget] = useComponentPermission(['edit_widget'], user.role);
@@ -114,7 +116,7 @@ function FullView({
graphType: getGraphType(selectedPanelType),
query: updatedQuery,
globalSelectedInterval: globalSelectedTime,
- variables: getDashboardVariables(selectedDashboard?.data.variables),
+ variables: getDashboardVariables(dashboardVariables),
fillGaps: widget.fillSpans,
formatForWeb: selectedPanelType === PANEL_TYPES.TABLE,
originalGraphType: selectedPanelType,
@@ -125,7 +127,7 @@ function FullView({
graphType: PANEL_TYPES.LIST,
selectedTime: widget?.timePreferance || 'GLOBAL_TIME',
globalSelectedInterval: globalSelectedTime,
- variables: getDashboardVariables(selectedDashboard?.data.variables),
+ variables: getDashboardVariables(dashboardVariables),
tableParams: {
pagination: {
offset: 0,
diff --git a/frontend/src/container/GridCardLayout/GridCard/index.tsx b/frontend/src/container/GridCardLayout/GridCard/index.tsx
index 0ef918ada5..8a3dc99cc2 100644
--- a/frontend/src/container/GridCardLayout/GridCard/index.tsx
+++ b/frontend/src/container/GridCardLayout/GridCard/index.tsx
@@ -53,7 +53,7 @@ function GridCardGraph({
customOnRowClick,
customTimeRangeWindowForCoRelation,
enableDrillDown,
- widgetsHavingDynamicVariables,
+ widgetsByDynamicVariableId,
}: GridCardGraphProps): JSX.Element {
const dispatch = useDispatch();
const [errorMessage, setErrorMessage] = useState<string>();
@@ -226,8 +226,8 @@ function GridCardGraph({
? Object.entries(variables).reduce((acc, [id, variable]) => {
if (
variable.type !== 'DYNAMIC' ||
- (widgetsHavingDynamicVariables?.[variable.id] &&
- widgetsHavingDynamicVariables?.[variable.id].includes(widget.id))
+ (widgetsByDynamicVariableId?.[variable.id] &&
+ widgetsByDynamicVariableId?.[variable.id].includes(widget.id))
) {
return { ...acc, [id]: variable.selectedValue };
}
diff --git a/frontend/src/container/GridCardLayout/GridCard/types.ts b/frontend/src/container/GridCardLayout/GridCard/types.ts
index 0f387cf3dd..85fcef854c 100644
--- a/frontend/src/container/GridCardLayout/GridCard/types.ts
+++ b/frontend/src/container/GridCardLayout/GridCard/types.ts
@@ -4,8 +4,9 @@ import { ToggleGraphProps } from 'components/Graph/types';
import { GetQueryResultsProps } from 'lib/dashboard/getQueryResults';
import { RowData } from 'lib/query/createTableColumnsFromQuery';
import { OnClickPluginOpts } from 'lib/uPlotLib/plugins/onClickPlugin';
+import { IDashboardVariables } from 'providers/Dashboard/store/dashboardVariablesStore';
import { SuccessResponse } from 'types/api';
-import { Dashboard, Widgets } from 'types/api/dashboard/getAll';
+import { Widgets } from 'types/api/dashboard/getAll';
import { MetricRangePayloadProps } from 'types/api/metrics/getQueryRange';
import { QueryData } from 'types/api/widgets/getQuery';
import uPlot from 'uplot';
@@ -50,7 +51,7 @@ export interface GridCardGraphProps {
headerMenuList?: WidgetGraphComponentProps['headerMenuList'];
onClickHandler?: OnClickPluginOpts['onClick'];
isQueryEnabled: boolean;
- variables?: Dashboard['data']['variables'];
+ variables?: IDashboardVariables;
version?: string;
onDragSelect: (start: number, end: number) => void;
customOnDragSelect?: (start: number, end: number) => void;
@@ -71,7 +72,7 @@ export interface GridCardGraphProps {
customOnRowClick?: (record: RowData) => void;
customTimeRangeWindowForCoRelation?: string | undefined;
enableDrillDown?: boolean;
- widgetsHavingDynamicVariables?: Record<string, string[]>;
+ widgetsByDynamicVariableId?: Record<string, string[]>;
}
export interface GetGraphVisibilityStateOnLegendClickProps {
diff --git a/frontend/src/container/GridCardLayout/GridCardLayout.tsx b/frontend/src/container/GridCardLayout/GridCardLayout.tsx
index f697f6cc22..c11c05112e 100644
--- a/frontend/src/container/GridCardLayout/GridCardLayout.tsx
+++ b/frontend/src/container/GridCardLayout/GridCardLayout.tsx
@@ -14,8 +14,9 @@ import { QueryParams } from 'constants/query';
import { PANEL_GROUP_TYPES, PANEL_TYPES } from 'constants/queryBuilder';
import { themeColors } from 'constants/theme';
import { DEFAULT_ROW_NAME } from 'container/DashboardContainer/DashboardDescription/utils';
+import { useDashboardVariables } from 'hooks/dashboard/useDashboardVariables';
import { useUpdateDashboard } from 'hooks/dashboard/useUpdateDashboard';
-import { createDynamicVariableToWidgetsMap } from 'hooks/dashboard/utils';
+import { useWidgetsByDynamicVariableId } from 'hooks/dashboard/useWidgetsByDynamicVariableId';
import useComponentPermission from 'hooks/useComponentPermission';
import { useIsDarkMode } from 'hooks/useDarkMode';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
@@ -34,7 +35,7 @@ import { useAppContext } from 'providers/App/App';
import { useDashboard } from 'providers/Dashboard/Dashboard';
import { sortLayout } from 'providers/Dashboard/util';
import { UpdateTimeInterval } from 'store/actions';
-import { IDashboardVariable, Widgets } from 'types/api/dashboard/getAll';
+import { Widgets } from 'types/api/dashboard/getAll';
import { Props } from 'types/api/dashboard/update';
import { ROLES, USER_ROLES } from 'types/roles';
import { ComponentTypes } from 'utils/permission';
@@ -79,7 +80,9 @@ function GraphLayout(props: GraphLayoutProps): JSX.Element {
const { pathname } = useLocation();
const dispatch = useDispatch();
- const { widgets, variables } = data || {};
+ const { widgets } = data || {};
+
+ const { dashboardVariables } = useDashboardVariables();
const { user } = useAppContext();
@@ -99,21 +102,7 @@ function GraphLayout(props: GraphLayoutProps): JSX.Element {
Record<string, { widgets: Layout[]; collapsed: boolean }>
>({});
- const widgetsHavingDynamicVariables = useMemo(() => {
- const dynamicVariables = Object.values(
- selectedDashboard?.data?.variables || {},
- )?.filter((variable: IDashboardVariable) => variable.type === 'DYNAMIC');
-
- const widgets =
- selectedDashboard?.data?.widgets?.filter(
- (widget) => widget.panelTypes !== PANEL_GROUP_TYPES.ROW,
- ) || [];
-
- return createDynamicVariableToWidgetsMap(
- dynamicVariables,
- widgets as Widgets[],
- );
- }, [selectedDashboard]);
+ const widgetsByDynamicVariableId = useWidgetsByDynamicVariableId();
useEffect(() => {
setCurrentPanelMap(panelMap);
@@ -178,11 +167,11 @@ function GraphLayout(props: GraphLayoutProps): JSX.Element {
dashboardId: selectedDashboard?.id,
dashboardName: data.title,
numberOfPanels: data.widgets?.length,
- numberOfVariables: Object.keys(data?.variables || {}).length || 0,
+ numberOfVariables: Object.keys(dashboardVariables).length || 0,
});
logEventCalledRef.current = true;
}
- }, [data, selectedDashboard?.id]);
+ }, [dashboardVariables, data, selectedDashboard?.id]);
const onSaveHandler = (): void => {
if (!selectedDashboard) {
@@ -622,13 +611,13 @@ function GraphLayout(props: GraphLayoutProps): JSX.Element {
<GridCard
widget={(currentWidget as Widgets) || ({ id, query: {} } as Widgets)}
headerMenuList={widgetActions}
- variables={variables}
+ variables={dashboardVariables}
// version={selectedDashboard?.data?.version}
version={ENTITY_VERSION_V5}
onDragSelect={onDragSelect}
dataAvailable={checkIfDataExists}
enableDrillDown={enableDrillDown}
- widgetsHavingDynamicVariables={widgetsHavingDynamicVariables}
+ widgetsByDynamicVariableId={widgetsByDynamicVariableId}
/>
</Card>
</CardContainer>
diff --git a/frontend/src/container/GridCardLayout/useResolveQuery.ts b/frontend/src/container/GridCardLayout/useResolveQuery.ts
index 1632914447..6d80200682 100644
--- a/frontend/src/container/GridCardLayout/useResolveQuery.ts
+++ b/frontend/src/container/GridCardLayout/useResolveQuery.ts
@@ -1,15 +1,14 @@
-import { useCallback, useMemo } from 'react';
+import { useCallback } from 'react';
import { useMutation } from 'react-query';
import { useSelector } from 'react-redux';
import { getSubstituteVars } from 'api/dashboard/substitute_vars';
import { prepareQueryRangePayloadV5 } from 'api/v5/v5';
import { PANEL_TYPES } from 'constants/queryBuilder';
import { timePreferenceType } from 'container/NewWidget/RightContainer/timeItems';
+import { useDashboardVariablesByType } from 'hooks/dashboard/useDashboardVariablesByType';
import { getDashboardVariables } from 'lib/dashbaordVariables/getDashboardVariables';
import { mapQueryDataFromApi } from 'lib/newQueryBuilder/queryBuilderMappers/mapQueryDataFromApi';
-import { useDashboard } from 'providers/Dashboard/Dashboard';
import { AppState } from 'store/reducers';
-import { IDashboardVariable } from 'types/api/dashboard/getAll';
import { Query } from 'types/api/queryBuilder/queryBuilderData';
import { GlobalReducer } from 'types/reducer/globalTime';
import { getGraphType } from 'utils/getGraphType';
@@ -36,14 +35,9 @@ function useUpdatedQuery(): UseUpdatedQueryResult {
const queryRangeMutation = useMutation(getSubstituteVars);
- const { selectedDashboard } = useDashboard();
-
- const dynamicVariables = useMemo(
- () =>
- Object.values(selectedDashboard?.data?.variables || {})?.filter(
- (variable: IDashboardVariable) => variable.type === 'DYNAMIC',
- ),
- [selectedDashboard],
+ const dashboardDynamicVariables = useDashboardVariablesByType(
+ 'DYNAMIC',
+ 'values',
);
const getUpdatedQuery = useCallback(
@@ -59,7 +53,7 @@ function useUpdatedQuery(): UseUpdatedQueryResult {
globalSelectedInterval,
variables: getDashboardVariables(selectedDashboard?.data?.variables),
originalGraphType: widgetConfig.panelTypes,
- dynamicVariables,
+ dynamicVariables: dashboardDynamicVariables,
});
// Execute query and process results
@@ -68,7 +62,7 @@ function useUpdatedQuery(): UseUpdatedQueryResult {
// Map query data from API response
return mapQueryDataFromApi(queryResult.data.compositeQuery);
},
- [dynamicVariables, globalSelectedInterval, queryRangeMutation],
+ [dashboardDynamicVariables, globalSelectedInterval, queryRangeMutation],
);
return {
diff --git a/frontend/src/container/NewWidget/RightContainer/index.tsx b/frontend/src/container/NewWidget/RightContainer/index.tsx
index 7fbdde6fd7..0bc733de2e 100644
--- a/frontend/src/container/NewWidget/RightContainer/index.tsx
+++ b/frontend/src/container/NewWidget/RightContainer/index.tsx
@@ -26,6 +26,7 @@ import { PANEL_TYPES, PanelDisplay } from 'constants/queryBuilder';
import GraphTypes, {
ItemsProps,
} from 'container/DashboardContainer/ComponentsSlider/menuItems';
+import { useDashboardVariables } from 'hooks/dashboard/useDashboardVariables';
import useCreateAlerts from 'hooks/queryBuilder/useCreateAlerts';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
import {
@@ -35,7 +36,6 @@ import {
Spline,
SquareArrowOutUpRight,
} from 'lucide-react';
-import { useDashboard } from 'providers/Dashboard/Dashboard';
import { SuccessResponse } from 'types/api';
import {
ColumnUnit,
@@ -131,7 +131,7 @@ function RightContainer({
enableDrillDown = false,
isNewDashboard,
}: RightContainerProps): JSX.Element {
- const { selectedDashboard } = useDashboard();
+ const { dashboardVariables } = useDashboardVariables();
const [inputValue, setInputValue] = useState(title);
const [autoCompleteOpen, setAutoCompleteOpen] = useState(false);
const [cursorPos, setCursorPos] = useState(0);
@@ -173,16 +173,12 @@ function RightContainer({
const [graphTypes, setGraphTypes] = useState<ItemsProps[]>(GraphTypes);
- // Get dashboard variables
- const dashboardVariables = useMemo<VariableOption[]>(() => {
- if (!selectedDashboard?.data?.variables) {
- return [];
- }
- return Object.entries(selectedDashboard.data.variables).map(([, value]) => ({
+ const dashboardVariableOptions = useMemo<VariableOption[]>(() => {
+ return Object.entries(dashboardVariables).map(([, value]) => ({
value: value.name || '',
label: value.name || '',
}));
- }, [selectedDashboard?.data?.variables]);
+ }, [dashboardVariables]);
const updateCursorAndDropdown = (value: string, pos: number): void => {
setCursorPos(pos);
@@ -274,7 +270,7 @@ function RightContainer({
<section className="name-description">
<Typography.Text className="typography">Name</Typography.Text>
<AutoComplete
- options={dashboardVariables}
+ options={dashboardVariableOptions}
value={inputValue}
onChange={onInputChange}
onSelect={onSelect}
diff --git a/frontend/src/container/NewWidget/index.tsx b/frontend/src/container/NewWidget/index.tsx
index 4ffd5b717b..ff198c6250 100644
--- a/frontend/src/container/NewWidget/index.tsx
+++ b/frontend/src/container/NewWidget/index.tsx
@@ -19,6 +19,7 @@ import {
import ROUTES from 'constants/routes';
import { DashboardShortcuts } from 'constants/shortcuts/DashboardShortcuts';
import { DEFAULT_BUCKET_COUNT } from 'container/PanelWrapper/constants';
+import { useDashboardVariables } from 'hooks/dashboard/useDashboardVariables';
import { useUpdateDashboard } from 'hooks/dashboard/useUpdateDashboard';
import { useKeyboardHotkeys } from 'hooks/hotkeys/useKeyboardHotkeys';
import { useQueryBuilder } from 'hooks/queryBuilder/useQueryBuilder';
@@ -89,6 +90,8 @@ function NewWidget({
columnWidths,
} = useDashboard();
+ const { dashboardVariables } = useDashboardVariables();
+
const { t } = useTranslation(['dashboard']);
const { registerShortcut, deregisterShortcut } = useKeyboardHotkeys();
@@ -377,7 +380,7 @@ function NewWidget({
graphType: PANEL_TYPES.LIST,
selectedTime: selectedTime.enum || 'GLOBAL_TIME',
globalSelectedInterval: customGlobalSelectedInterval,
- variables: getDashboardVariables(selectedDashboard?.data.variables),
+ variables: getDashboardVariables(dashboardVariables),
tableParams: {
pagination: {
offset: 0,
@@ -394,7 +397,7 @@ function NewWidget({
formatForWeb:
getGraphTypeForFormat(selectedGraph || selectedWidget.panelTypes) ===
PANEL_TYPES.TABLE,
- variables: getDashboardVariables(selectedDashboard?.data.variables),
+ variables: getDashboardVariables(dashboardVariables),
originalGraphType: selectedGraph || selectedWidget?.panelTypes,
};
}
@@ -408,7 +411,7 @@ function NewWidget({
graphType: selectedGraph,
selectedTime: selectedTime.enum || 'GLOBAL_TIME',
globalSelectedInterval: customGlobalSelectedInterval,
- variables: getDashboardVariables(selectedDashboard?.data.variables),
+ variables: getDashboardVariables(dashboardVariables),
};
});
diff --git a/frontend/src/hooks/dashboard/__test__/useGetResolvedText.test.tsx b/frontend/src/hooks/dashboard/__test__/useGetResolvedText.test.tsx
index d7e88ccbe7..1081265159 100644
--- a/frontend/src/hooks/dashboard/__test__/useGetResolvedText.test.tsx
+++ b/frontend/src/hooks/dashboard/__test__/useGetResolvedText.test.tsx
@@ -1,15 +1,17 @@
import React from 'react';
import { renderHook } from '@testing-library/react';
+import { IDashboardVariables } from 'providers/Dashboard/store/dashboardVariablesStore';
import useGetResolvedText from '../useGetResolvedText';
-// Mock the useDashboard hook
-jest.mock('providers/Dashboard/Dashboard', () => ({
- useDashboard: function useDashboardMock(): any {
- return {
- selectedDashboard: null,
- };
- },
+// Create a mock function that we can modify per test
+let mockDashboardVariables: IDashboardVariables = {};
+
+// Mock the useDashboardVariables hook
+jest.mock('hooks/dashboard/useDashboardVariables', () => ({
+ useDashboardVariables: jest.fn(() => ({
+ dashboardVariables: mockDashboardVariables,
+ })),
}));
describe('useGetResolvedText', () => {
@@ -20,13 +22,35 @@ describe('useGetResolvedText', () => {
const TRUNCATED_SERVICE = 'test, app +2';
const TEXT_TEMPLATE = 'Logs count in $service.name in $severity';
- const renderHookWithProps = (props: {
- text: string | React.ReactNode;
- variables?: Record<string, string | number | boolean>;
- dashboardVariables?: Record<string, any>;
- maxLength?: number;
- matcher?: string;
- }): any => renderHook(() => useGetResolvedText(props));
+ const renderHookWithProps = (
+ props: {
+ text: string | React.ReactNode;
+ maxLength?: number;
+ matcher?: string;
+ },
+ variables?: Record<string, string | number | boolean>,
+ ): any => {
+ if (variables) {
+ mockDashboardVariables = Object.entries(
+ variables,
+ ).reduce<IDashboardVariables>((acc, [key, value]) => {
+ acc[key] = {
+ id: key,
+ name: key,
+ description: '',
+ type: 'CUSTOM' as const,
+ sort: 'DISABLED' as const,
+ multiSelect: false,
+ showALLOption: false,
+ selectedValue: value,
+ };
+ return acc;
+ }, {});
+ } else {
+ mockDashboardVariables = {};
+ }
+ return renderHook(() => useGetResolvedText(props));
+ };
it('should resolve variables with truncated and full text', () => {
const text = TEXT_TEMPLATE;
@@ -35,7 +59,7 @@ describe('useGetResolvedText', () => {
severity: SEVERITY_VAR,
};
- const { result } = renderHookWithProps({ text, variables });
+ const { result } = renderHookWithProps({ text }, variables);
expect(result.current.truncatedText).toBe(
`Logs count in ${TRUNCATED_SERVICE} in DEBUG, INFO`,
@@ -50,7 +74,7 @@ describe('useGetResolvedText', () => {
severity: SEVERITY_VAR,
};
- const { result } = renderHookWithProps({ text, variables, maxLength: 20 });
+ const { result } = renderHookWithProps({ text, maxLength: 20 }, variables);
expect(result.current.truncatedText).toBe('Logs count in test, a...');
expect(result.current.fullText).toBe(EXPECTED_FULL_TEXT);
@@ -62,7 +86,7 @@ describe('useGetResolvedText', () => {
'service.name': SERVICE_VAR,
};
- const { result } = renderHookWithProps({ text, variables });
+ const { result } = renderHookWithProps({ text }, variables);
expect(result.current.truncatedText).toBe(
'Logs count in test, app +2 and test, app +2',
@@ -80,7 +104,7 @@ describe('useGetResolvedText', () => {
'$dyn-service.name': 'dyn-1, dyn-2',
};
- const { result } = renderHookWithProps({ text, variables });
+ const { result } = renderHookWithProps({ text }, variables);
expect(result.current.truncatedText).toBe(
'Logs in test, app +2, test, app +2, test, app +2 - dyn-1, dyn-2',
@@ -97,7 +121,7 @@ describe('useGetResolvedText', () => {
severity: SEVERITY_VAR,
};
- const { result } = renderHookWithProps({ text, variables, matcher: '#' });
+ const { result } = renderHookWithProps({ text, matcher: '#' }, variables);
expect(result.current.truncatedText).toBe(
'Logs count in test, app +2 in DEBUG, INFO',
@@ -112,7 +136,7 @@ describe('useGetResolvedText', () => {
active: true,
};
- const { result } = renderHookWithProps({ text, variables });
+ const { result } = renderHookWithProps({ text }, variables);
expect(result.current.fullText).toBe('Count: 42, Active: true');
expect(result.current.truncatedText).toBe('Count: 42, Active: true');
@@ -124,7 +148,7 @@ describe('useGetResolvedText', () => {
'service.name': SERVICE_VAR,
};
- const { result } = renderHookWithProps({ text, variables });
+ const { result } = renderHookWithProps({ text }, variables);
expect(result.current.truncatedText).toBe(
'Logs count in test, app +2 in $unknown',
@@ -140,10 +164,12 @@ describe('useGetResolvedText', () => {
'service.name': SERVICE_VAR,
};
- const { result } = renderHookWithProps({
- text: reactNodeText,
+ const { result } = renderHookWithProps(
+ {
+ text: reactNodeText,
+ },
variables,
- });
+ );
// Should return the ReactNode unchanged
expect(result.current.fullText).toBe(reactNodeText);
@@ -156,10 +182,12 @@ describe('useGetResolvedText', () => {
'service.name': SERVICE_VAR,
};
- const { result } = renderHookWithProps({
- text,
+ const { result } = renderHookWithProps(
+ {
+ text,
+ },
variables,
- });
+ );
// Should return the number unchanged
expect(result.current.fullText).toBe(text);
@@ -172,10 +200,12 @@ describe('useGetResolvedText', () => {
'service.name': SERVICE_VAR,
};
- const { result } = renderHookWithProps({
- text,
+ const { result } = renderHookWithProps(
+ {
+ text,
+ },
variables,
- });
+ );
// Should return the boolean unchanged
expect(result.current.fullText).toBe(text);
@@ -189,7 +219,7 @@ describe('useGetResolvedText', () => {
'config.database.host': 'localhost:5432',
};
- const { result } = renderHookWithProps({ text, variables });
+ const { result } = renderHookWithProps({ text }, variables);
expect(result.current.fullText).toBe('API: /users Config: localhost:5432');
expect(result.current.truncatedText).toBe(
@@ -204,7 +234,7 @@ describe('useGetResolvedText', () => {
'error.type': 'timeout',
};
- const { result } = renderHookWithProps({ text, variables });
+ const { result } = renderHookWithProps({ text }, variables);
expect(result.current.fullText).toBe('Status: web-api, Error: timeout;');
expect(result.current.truncatedText).toBe('Status: web-api, Error: timeout;');
diff --git a/frontend/src/hooks/dashboard/useContextVariables.tsx b/frontend/src/hooks/dashboard/useContextVariables.tsx
index 99c0e87d95..2f95147e2b 100644
--- a/frontend/src/hooks/dashboard/useContextVariables.tsx
+++ b/frontend/src/hooks/dashboard/useContextVariables.tsx
@@ -1,6 +1,6 @@
import { useMemo } from 'react';
import { useSelector } from 'react-redux';
-import { useDashboard } from 'providers/Dashboard/Dashboard';
+import { useDashboardVariables } from 'hooks/dashboard/useDashboardVariables';
import { AppState } from 'store/reducers';
import { GlobalReducer } from 'types/reducer/globalTime';
@@ -38,20 +38,17 @@ interface ResolvedTextUtilsResult {
function useContextVariables({
maxValues = 2,
+ // ! To be noted: This customVariables is not Dashboard Custom Variables
customVariables,
}: UseContextVariablesProps): UseContextVariablesResult {
- const { selectedDashboard } = useDashboard();
+ const { dashboardVariables } = useDashboardVariables();
const globalTime = useSelector<AppState, GlobalReducer>(
(state) => state.globalTime,
);
// Extract dashboard variables
- const dashboardVariables = useMemo(() => {
- if (!selectedDashboard?.data?.variables) {
- return [];
- }
-
- return Object.entries(selectedDashboard.data.variables)
+ const processedDashboardVariables = useMemo(() => {
+ return Object.entries(dashboardVariables)
.filter(([, value]) => value.name)
.map(([, value]) => {
let processedValue: string | number | boolean;
@@ -74,7 +71,7 @@ function useContextVariables({
originalValue: value.selectedValue,
};
});
- }, [selectedDashboard]);
+ }, [dashboardVariables]);
// Extract global variables
const globalVariables = useMemo(
@@ -111,8 +108,12 @@ function useContextVariables({
// Combine all variables
const allVariables = useMemo(
- () => [...dashboardVariables, ...globalVariables, ...customVariablesList],
- [dashboardVariables, globalVariables, customVariablesList],
+ () => [
+ ...processedDashboardVariables,
+ ...globalVariables,
+ ...customVariablesList,
+ ],
+ [processedDashboardVariables, globalVariables, customVariablesList],
);
// Create processed variables with truncation logic
diff --git a/frontend/src/hooks/dashboard/useGetResolvedText.tsx b/frontend/src/hooks/dashboard/useGetResolvedText.tsx
index 59d19b7671..a8409dc10e 100644
--- a/frontend/src/hooks/dashboard/useGetResolvedText.tsx
+++ b/frontend/src/hooks/dashboard/useGetResolvedText.tsx
@@ -5,7 +5,7 @@
// return value should be a full text string, and a truncated text string (if max length is provided)
import { ReactNode, useCallback, useMemo } from 'react';
-import { useDashboard } from 'providers/Dashboard/Dashboard';
+import { useDashboardVariables } from 'hooks/dashboard/useDashboardVariables';
interface UseGetResolvedTextProps {
text: string | ReactNode;
@@ -23,23 +23,15 @@ interface ResolvedTextResult {
// eslint-disable-next-line sonarjs/cognitive-complexity
function useGetResolvedText({
text,
- variables,
maxLength,
matcher = '$',
maxValues = 2, // Default to showing 2 values before +n more
}: UseGetResolvedTextProps): ResolvedTextResult {
- const { selectedDashboard } = useDashboard();
+ const { dashboardVariables } = useDashboardVariables();
const isString = typeof text === 'string';
const processedDashboardVariables = useMemo(() => {
- if (variables) {
- return variables;
- }
- if (!selectedDashboard?.data.variables) {
- return {};
- }
-
- return Object.entries(selectedDashboard.data.variables).reduce<
+ return Object.entries(dashboardVariables).reduce<
Record<string, string | number | boolean>
>((acc, [, value]) => {
if (!value.name) {
@@ -54,7 +46,7 @@ function useGetResolvedText({
}
return acc;
}, {});
- }, [variables, selectedDashboard?.data.variables]);
+ }, [dashboardVariables]);
// Process array values to add +n more notation for truncated text
const processedVariables = useMemo(() => {