use-minimal-fetch
Version:
A lightweight useFetch hook with Axios wrapper for React apps
27 lines (26 loc) • 750 B
JavaScript
import { useState } from "react";
import api from "../lib/api";
export const usePost = (url, options = {}) => {
const { headers } = options;
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
const post = async (payload) => {
setLoading(true);
try {
const res = await api.post(url, payload, { headers });
setData(res.data);
setError(null);
return res.data;
}
catch (err) {
setError(err);
setData(null);
throw err;
}
finally {
setLoading(false);
}
};
return { data, loading, error, post };
};