Skip to content

Commit

Permalink
fix/usefeaturesearch cache (#5340)
Browse files Browse the repository at this point in the history
Fixes a bug where the closure over the useFeatureSearch hook would not
account for projectId and return the wrong total/initial load
  • Loading branch information
FredrikOseberg authored Nov 15, 2023
1 parent 142e322 commit db77962
Showing 1 changed file with 43 additions and 8 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import useSWR, { SWRConfiguration } from 'swr';
import { useCallback } from 'react';
import { useCallback, useEffect } from 'react';
import { IFeatureToggleListItem } from 'interfaces/featureToggle';
import { formatApiPath } from 'utils/formatPath';
import handleErrorResponses from '../httpErrorResponseHandler';
Expand All @@ -19,6 +19,14 @@ interface IUseFeatureSearchOutput {
refetch: () => void;
}

type CacheValue = {
total: number;
initialLoad: boolean;
[key: string]: number | boolean;
};

type InternalCache = Record<string, CacheValue>;

const fallbackData: {
features: IFeatureToggleListItem[];
total: number;
Expand All @@ -28,8 +36,28 @@ const fallbackData: {
};

const createFeatureSearch = () => {
let total = 0;
let initialLoad = true;
const internalCache: InternalCache = {};

const initCache = (projectId: string) => {
internalCache[projectId] = {
total: 0,
initialLoad: true,
};
};

const set = (projectId: string, key: string, value: number | boolean) => {
if (!internalCache[projectId]) {
initCache(projectId);
}
internalCache[projectId][key] = value;
};

const get = (projectId: string) => {
if (!internalCache[projectId]) {
initCache(projectId);
}
return internalCache[projectId];
};

return (
offset: number,
Expand All @@ -44,19 +72,26 @@ const createFeatureSearch = () => {
limit,
searchValue,
);

useEffect(() => {
initCache(projectId);
}, []);

const { data, error, mutate, isLoading } =
useSWR<IFeatureSearchResponse>(KEY, fetcher, options);

const refetch = useCallback(() => {
mutate();
}, [mutate]);

const cacheValues = get(projectId);

if (data?.total) {
total = data.total;
set(projectId, 'total', data.total);
}

if (!isLoading && initialLoad) {
initialLoad = false;
if (!isLoading && cacheValues.initialLoad) {
set(projectId, 'initialLoad', false);
}

const returnData = data || fallbackData;
Expand All @@ -65,8 +100,8 @@ const createFeatureSearch = () => {
loading: isLoading,
error,
refetch,
total,
initialLoad: isLoading && initialLoad,
total: cacheValues.total,
initialLoad: isLoading && cacheValues.initialLoad,
};
};
};
Expand Down

0 comments on commit db77962

Please sign in to comment.