use-query-rd
Version:
A drop in replacement for apollo client's `useQuery` hook with a return type that mimics Elm's RemoteData ADT
56 lines • 2.04 kB
JavaScript
;
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.useQueryRd = void 0;
var client_1 = require("@apollo/client");
var rd_1 = require("./rd");
/**
* @description Maps a `useQuery` QueryResult status (called | loading | data | error) to the RemoteData union
* @param query GQL query document
* @param options useQuery opts
* @see https://www.apollographql.com/docs/react/data/queries/
* @note RemoteData is tagged with `tag`. There is no generic for Error as it will always be an ApolloError.
* @returns Everything from `QueryResult` with an accompanying `_rd` property wth the RemoteData object
*/
var useQueryRd = function () {
var params = [];
for (var _i = 0; _i < arguments.length; _i++) {
params[_i] = arguments[_i];
}
var res = client_1.useQuery.apply(void 0, params);
if (!res.called) {
return __assign(__assign({}, res), { _rd: {
tag: rd_1.Tags.Initialized
} });
}
if (res.loading) {
return __assign(__assign({}, res), { _rd: {
tag: rd_1.Tags.Pending
} });
}
if (res.data !== null && res.data !== undefined) {
return __assign(__assign({}, res), { _rd: {
tag: rd_1.Tags.Success,
data: res.data
} });
}
if (res.error !== null && res.error !== undefined) {
return __assign(__assign({}, res), { _rd: {
tag: rd_1.Tags.Failure,
error: res.error
} });
}
throw new TypeError('RemoteData case not matched');
};
exports.useQueryRd = useQueryRd;
//# sourceMappingURL=useQueryRd.js.map