@rocketmakers/api-swr
Version:
Rocketmakers front-end library for parsing a generated Typescript API client into a set of configurable React hooks for fetching and mutating data.
39 lines (38 loc) • 1.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useContentMemo = void 0;
const tslib_1 = require("tslib");
/*
* useContentMemo
* --------------------------------------
* Utility hook for content based memoization
*/
const React = tslib_1.__importStar(require("react"));
/**
* Returns a reference to the passed in item which only updates when the *content* of the item updates rather than just the pointer reference
* WARNING: This hook was designed for config/state objects and assumes that array/object items are serializable
* @param item The item to pass a reference for
* @returns A memoized version of the item passed in
*/
const useContentMemo = (item) => {
const contentDependency = React.useMemo(() => {
// falsy item or function, all we can do is return the reference like a normal memo
if (!item || typeof item === 'function') {
return item;
}
// sort array and serialize it for primitive comparison
if (Array.isArray(item)) {
return JSON.stringify([...item].sort());
}
// sort object keys and serialize it for primitive comparison
if (typeof item === 'object') {
return JSON.stringify(Object.keys(item)
.sort()
.reduce((memo, key) => (Object.assign(Object.assign({}, memo), { [key]: item[key] })), {}));
}
// stringify primitive for comparison
return `${item}`;
}, [item]);
return React.useMemo(() => item, [contentDependency]);
};
exports.useContentMemo = useContentMemo;