react-ketting
Version:
Ketting bindings for React
72 lines • 2.53 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.useResource = void 0;
const use_read_resource_1 = require("./use-read-resource");
/**
* The useResource hook allows you to GET and PUT the state of
* a resource.
*
* Example call:
*
* <pre>
* const {
* loading,
* error,
* resourceState,
* setResourceState,
* submit
* } = useResource(resource);
* </pre>
*
* 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.
* * resourceState - A state object. The `.data` property of this object will
* contain the parsed JSON from the server.
* * setResourceState - Update the local cache of the resource.
* * submit - Send a PUT request to the server.
*
* If you don't need the full resourceState, you can also use the `data` and
* `setData` properties instead of `resourceState` or `useResourceState`.
*/
function useResource(resourceLike, options) {
if (resourceLike === undefined) {
console.warn('useResource was called with "undefined" as the "resourceLike" argument. This is a bug. Did you forget to wait for \'loading\' to complete somewhere?');
}
const { resourceState, loading, error, resource } = (0, use_read_resource_1.useReadResource)(resourceLike, {
refreshOnStale: options === null || options === void 0 ? void 0 : options.refreshOnStale,
});
const setResourceState = (newState) => {
if (!resource) {
throw new Error('Too early to call setResourceState, we don\'t have a current state to update');
}
resource.updateCache(newState);
};
const submit = async () => {
if (!resourceState || !resource) {
throw new Error('Too early to call submit()');
}
await resource.put(resourceState);
};
const setData = (newData) => {
if (!resourceState || !resource) {
throw new Error('Too early to call setData, we don\'t have a current state to update');
}
resourceState.data = newData;
setResourceState(resourceState);
};
return {
loading,
error,
data: resourceState === null || resourceState === void 0 ? void 0 : resourceState.data,
setData,
resourceState,
setResourceState,
resource,
submit,
};
}
exports.useResource = useResource;
//# sourceMappingURL=use-resource.js.map
;