@knowmax/genericlist-core
Version:
Knowmax Generic list with basic CRUD support without any user interface implementation.
48 lines (47 loc) • 2.19 kB
JavaScript
import { useEffect, useMemo } from "react";
import { deserializeListState } from "../utils";
import { useGenericListCache } from "./GenericListCacheProvider";
import { GenericList, useGenericListSettings } from '.';
/**
* Generic hook for specified type and configuration. Attempts to cache lists using endpoint as key.
* Automatically loads data, updates token and selected application.
*
* @param configuration - List configuration including endpoint and other settings
* @param autoLoad - Whether to automatically load data when the list is created or dependencies change
* @param cache - Whether to use caching. When true, lists are cached by endpoint/id key
* @param dependencies - Optional custom dependencies. When any of these change, the cached list (if any)
* will be removed and a fresh list instance will be created
*/
export const useList = (configuration, autoLoad = true, cache = true, dependencies) => {
const listsettings = useGenericListSettings();
const listcache = useGenericListCache();
const list = useMemo(() => {
if (cache) {
const key = configuration.id ? `${configuration.id}:${configuration.endpoint}` : configuration.endpoint;
// If custom dependencies are provided, remove the existing cached list first
// to ensure we get a fresh instance when dependencies change
if (dependencies) {
listcache.remove(key);
}
return listcache.getOrCreate(key, () => new GenericList(configuration));
}
else {
return new GenericList(configuration);
}
}, [cache, configuration.endpoint, configuration.id, listcache, ...(dependencies || [])]);
useEffect(() => {
list.setSettings(listsettings);
}, [list, listsettings]);
useEffect(() => {
const params = new URLSearchParams(listsettings.params);
if (deserializeListState(list, params)) {
listsettings.serialize(params);
}
}, [list, listsettings.params]);
useEffect(() => {
if (autoLoad) {
list.load();
}
}, [list.hash, list, autoLoad]);
return list;
};