react-ketting
Version:
Ketting bindings for React
65 lines • 2.28 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.useCollection = void 0;
const react_1 = require("react");
const use_read_resource_1 = require("./use-read-resource");
/**
* The useCollection hook allows you to get a list of resources
* inside a collection.
*
* This hook makes a few assumptions:
*
* 1. The collection is some hypermedia document, such as HAL, HTML, Siren,
* or anything Ketting supports.
* 2. The collection lists its members via 'item' web links.
*
* Example call:
*
* <pre>
* const {
* loading,
* error,
* items
* } = useResource<Article>(resource);
* </pre>
*
* The resource may be passed as a Resource object, a Promise<Resource>, or a
* uri string.
*
* Returned properties:
*
* * loading - will be true as long as the result is still being fetched from
* the server.
* * error - Will be null or an error object.
* * items - Will contain an array of resources, each typed Resource<T> where
* T is the passed generic argument.
*/
function useCollection(resourceLike, options) {
if (resourceLike === undefined) {
console.warn('useCollection was called with "undefined" as the "resourceLike" argument. This is a bug. Did you forget to wait for \'loading\' to complete somewhere?');
}
const rel = (options === null || options === void 0 ? void 0 : options.rel) || 'item';
const { resource, resourceState, loading, error } = (0, use_read_resource_1.useReadResource)(resourceLike, {
refreshOnStale: options === null || options === void 0 ? void 0 : options.refreshOnStale,
// This header will be included on the first, uncached fetch.
// This may be helpful to the server and instruct it to embed
// all collection members in that initial fetch.
initialGetRequestHeaders: {
Prefer: 'transclude=' + rel,
}
});
const items = (0, react_1.useMemo)(() => {
if (!resourceState)
return [];
return resourceState.followAll(rel);
}, [resourceState]);
return {
loading,
error,
items,
resource,
resourceState,
};
}
exports.useCollection = useCollection;
//# sourceMappingURL=use-collection.js.map
;