Files
karma/ui/src/Hooks/useFetchDelete.ts
2020-07-22 21:39:43 +01:00

62 lines
1.5 KiB
TypeScript

import { useState, useEffect } from "react";
import merge from "lodash.merge";
import { CommonOptions } from "Common/Fetch";
type useFetchDeleteDepsT = string[] | number[];
const useFetchDelete = (
uri: string,
options: RequestInit,
deps: useFetchDeleteDepsT = []
): {
response: null | string;
error: null | string;
isDeleting: boolean;
} => {
const [response, setResponse] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [isDeleting, setIsDeleting] = useState<boolean>(true);
useEffect(() => {
// https://dev.to/pallymore/clean-up-async-requests-in-useeffect-hooks-90h
let isCancelled = false;
const fetchData = async () => {
try {
setIsDeleting(true);
const res = await fetch(
uri,
merge({}, { method: "DELETE" }, CommonOptions, options)
);
const text = await res.text();
if (!isCancelled) {
if (res.ok) {
setResponse(text);
setIsDeleting(false);
} else {
setError(text);
setIsDeleting(false);
}
}
} catch (error) {
if (!isCancelled) {
setError(error.message);
setIsDeleting(false);
}
}
};
fetchData();
return () => {
isCancelled = true;
};
}, [uri, options, ...deps]); // eslint-disable-line react-hooks/exhaustive-deps
return { response, error, isDeleting };
};
export { useFetchDelete };