1
0
mirror of https://github.com/Unleash/unleash.git synced 2024-12-22 19:07:54 +01:00

fix/usefeaturesearch cache (#5340)

Fixes a bug where the closure over the useFeatureSearch hook would not
account for projectId and return the wrong total/initial load
This commit is contained in:
Fredrik Strand Oseberg 2023-11-15 11:09:13 +01:00 committed by GitHub
parent 142e322589
commit db77962a72
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -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';
@ -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;
@ -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,
@ -44,6 +72,11 @@ const createFeatureSearch = () => {
limit,
searchValue,
);
useEffect(() => {
initCache(projectId);
}, []);
const { data, error, mutate, isLoading } =
useSWR<IFeatureSearchResponse>(KEY, fetcher, options);
@ -51,12 +84,14 @@ const createFeatureSearch = () => {
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;
@ -65,8 +100,8 @@ const createFeatureSearch = () => {
loading: isLoading,
error,
refetch,
total,
initialLoad: isLoading && initialLoad,
total: cacheValues.total,
initialLoad: isLoading && cacheValues.initialLoad,
};
};
};