Code Insights: Make sort over a new series settings array to avoid strange mutation
Created by: vovakulikov
Problem
In code insights codebase we have this code
export function createViewContent(
insight: InsightFields,
seriesSettings: SearchBasedInsightSeries[] = []
): LineChartContent<{ dateTime: number; [seriesKey: string]: number }, 'dateTime'> {
const sortedSeriesSettings = seriesSettings.sort((a, b) => a.query.localeCompare(b.query))
/* further logic ... */
}
As you can see in this function we call .sort()
array method, but this method changes the original seriesSettings
array and not produces a new array (mutation over immutability).
In BackendInsight.tsx
we rely on insight configuration object memoization to avoid unnecessary data fetching.
With that mutation, we break this memorization since each renders we will call .sort which changes array by reference in memo cache, and then in the next render memorization check will fail and we already run this mutation sort logic and again ...
As a result, we can see this behavior
We re-fetch BE insight each time when the number of insights on the dashboard page has been changed. But this is totally unnecessary since the insight configuration of this insight hasn't changed so we can be sure we don't need to update insight data there.
Fix
This PR just runs a sort mutation operation over a new array and avoids memorization failure.