use-minimal-fetch
Version:
A lightweight useFetch hook with Axios wrapper for React apps
52 lines (51 loc) • 1.66 kB
JavaScript
import { useState, useEffect } from "react";
import api from "../lib/api";
export const useApi = (url, options = {}) => {
const { method = "get", lazy = method !== "get", // GET auto-loads, others wait
params, headers, body } = options;
const [data, setData] = useState(null);
const [loading, setLoading] = useState(!lazy);
const [error, setError] = useState(null);
const execute = async (overrideBody) => {
setLoading(true);
try {
const config = { params, headers };
const payload = overrideBody ?? body;
let res;
switch (method) {
case "get":
res = await api.get(url, config);
break;
case "post":
res = await api.post(url, payload, config);
break;
case "put":
res = await api.put(url, payload, config);
break;
case "patch":
res = await api.patch(url, payload, config);
break;
case "delete":
res = await api.delete(url, config);
break;
}
setData(res?.data ?? null);
setError(null);
return res?.data;
}
catch (err) {
setError(err);
setData(null);
throw err;
}
finally {
setLoading(false);
}
};
useEffect(() => {
if (!lazy && method === "get") {
execute();
}
}, [url]);
return { data, loading, error, execute };
};