Hooks made based on the useQuery and useMutation of the apollo client, with an extra function to cancel requests. Can be useful when the component is unmounting and there is a request in progress.
- useCancellableQuery
- useCancellableMutation
Using npm:
$ npm install use-cancellable-query
Using yarn:
$ yarn add use-cancellable-query
When calling the cancel
function, the refetch
promise will be rejected with error.name = "AbortError"
and onCompleted
and onError
will not be executed.
import { useCancellableQuery } from 'use-cancellable-query';
// ...
// Inside your component
const { data, error, refetch, cancel } = useCancellableQuery(YOUR_QUERY, {
onCompleted: (data) => {
// some code
},
onError: (error) => {
// some code
},
});
function usingRefetch() {
refetch()
.then((response) => {
// some code
})
.catch((error) => {
if (error.name === 'AbortError') return;
// some code
});
}
// Cancel Request
cancel();
// ...
When calling the cancel
function, the refetch
promise will be rejected with error.name = "AbortError"
and onCompleted
and onError
will not be executed.
import { useCancellableMutation } from 'use-cancellable-query';
// ...
// Inside your component
const [mutation, { cancel }] = useCancellableMutation(YOUR_MUTATION, {
onCompleted: (data) => {
// some code
},
onError: (error) => {
// some code
},
});
function usingMutation() {
mutation()
.then((response) => {
// some code
})
.catch((error) => {
if (error.name === 'AbortError') return;
// some code
});
}
// Cancel Request
cancel();
// ...