Skip to content

Commit

Permalink
Merge branch 'feature/ADCM-5231' into 'develop'
Browse files Browse the repository at this point in the history
feature/ADCM-5231 + loaded data validator for usePersistSettings hook

See merge request arenadata/development/adcm!3572
  • Loading branch information
remizov-arena committed Jan 29, 2024
2 parents c48537a + 1047b66 commit 2bf4fdb
Showing 1 changed file with 37 additions and 4 deletions.
41 changes: 37 additions & 4 deletions adcm-web/app/src/hooks/usePersistSettings.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,37 @@ type UsePersistSettingsProps<T> = {
settings: T;
isReadyToLoad: boolean;
onSettingsLoaded: (settings: T) => void;
loadedDataValidator?: (loadedData: T, data: T) => boolean;
};

const getTableSettingKey = (userName: string, tableKey: string) => `${userName}_${tableKey}`;

const defaultLoadedDataValidator = (loadedData: unknown, data: unknown) => {
const dataType = typeof data;
const loadedDataType = typeof loadedData;
if (dataType !== loadedDataType) {
return false;
}

// check 1st level keys similarity
if (loadedData && loadedDataType === 'object' && data && dataType === 'object') {
const loadedDataKeys = new Set(Object.keys(loadedData));
const dataKeys = Object.keys(data);

if (loadedDataKeys.size === dataKeys.length) {
for (const key of dataKeys) {
if (!loadedDataKeys.has(key)) {
return false;
}
}

return true;
}
}

return false;
};

const mergePaginationParams = (perPage: number | undefined, paginationParams: PaginationParams): PaginationParams => {
return perPage === undefined
? paginationParams
Expand All @@ -32,12 +59,18 @@ export const usePersistSettings = <T>(props: UsePersistSettingsProps<T>, deps: u
});

useEffect(() => {
if (props.isReadyToLoad && dataFromLocalStorage && !isLoaded) {
props.onSettingsLoaded(dataFromLocalStorage);
setIsLoaded(true);
if (props.isReadyToLoad && !isLoaded) {
const loadedDataValidator = props.loadedDataValidator ?? defaultLoadedDataValidator;
const isValid = loadedDataValidator(dataFromLocalStorage as T, props.settings);
const validData = isValid ? dataFromLocalStorage : props.settings;

if (validData) {
props.onSettingsLoaded(validData);
setIsLoaded(true);
}
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [props.isReadyToLoad, dataFromLocalStorage, isLoaded]);
}, [props.isReadyToLoad, props.loadedDataValidator, dataFromLocalStorage, isLoaded]);

useEffect(() => {
if (isLoaded) {
Expand Down

0 comments on commit 2bf4fdb

Please sign in to comment.