@gqty/react
Version:
The No-GraphQL Client for React
69 lines (66 loc) • 2.19 kB
JavaScript
import { GQtyError } from 'gqty';
import * as React from 'react';
const createUseRefetch = (client, { defaults: { retry: defaultRetry } }) => {
const useRefetch = ({
notifyOnNetworkStatusChange = true,
operationName,
startWatching = true,
retry = defaultRetry,
suspense = false
} = {}) => {
const [state, setState] = React.useState();
const watchingRef = React.useRef(startWatching);
const [selections] = React.useState(() => /* @__PURE__ */ new Set());
const [unsubscribeSelections] = React.useState(
() => client.subscribeLegacySelections((selection) => {
if (watchingRef.current && selection.root.key === "query") {
selections.add(selection);
}
})
);
React.useEffect(() => unsubscribeSelections, [unsubscribeSelections]);
if (suspense) {
if (state == null ? void 0 : state.promise) throw state == null ? void 0 : state.promise;
if (state == null ? void 0 : state.error) throw state == null ? void 0 : state.error;
}
const refetch = React.useCallback(
async (fnArg) => {
const promise = (() => {
if (fnArg) return client.refetch(fnArg);
const { context, resolve } = client.createResolver({
retryPolicy: retry,
operationName
});
selections.forEach((selection) => {
context.select(selection);
});
return resolve();
})();
setState({ promise });
try {
return await promise;
} catch (error) {
const theError = GQtyError.create(error);
setState({ error: theError });
throw theError;
}
},
[notifyOnNetworkStatusChange, operationName, retry]
);
return React.useMemo(
() => Object.assign(refetch, {
isLoading: (state == null ? void 0 : state.promise) !== void 0,
error: state == null ? void 0 : state.error,
startWatching: () => {
watchingRef.current = true;
},
stopWatching: () => {
watchingRef.current = false;
}
}),
[]
);
};
return useRefetch;
};
export { createUseRefetch };