Skip to content

Code Insights: Make sort over a new series settings array to avoid strange mutation

Administrator requested to merge vk/fix-series-array-mutation into main

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

https://user-images.githubusercontent.com/18492575/131121944-49795338-3497-495f-b2ef-17fe1678ae38.mov

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.

https://user-images.githubusercontent.com/18492575/131122352-400b1c34-2031-470b-b823-c3d9fe92635f.mov

Merge request reports

Loading