useFetch
is a simple, reusable JavaScript package designed to streamline the process of making HTTP requests in web applications. It supports the four main HTTP methods (GET
, POST
, PATCH
, PUT
, DELETE
) and provides a clean and flexible way to send requests and handle responses.
To use useFetch
in your project, simply install it via npm:
npm i @breffjaun/usefetch
Import useFetch
into your application and use the provided methods to send HTTP requests.
import useFetch from "@breffjaun/usefetch"
-
get(url, func, options)
: Sends a GET request to the specified URL. -
post(url, data, func, options)
: Sends a POST request to the specified URL with the provided data. -
patch(url, data, func, options)
: Sends a PATCH request to the specified URL with the provided data. -
put(url, data, func, options)
: Sends a PUT request to the specified URL with the provided data. -
delete(url, func, options)
: Sends a DELETE request to the specified URL.
The options
parameter is optional and can be used to specify additional request options such as headers, credentials, cache behavior, etc.
useFetch
provides basic error handling, including checking the response status and handling network errors.
// Example of a GET request
const url = "https://api.example.com/data";
const [data, setData] = useState({});
useEffect(() => {
useFetch.get(url, setData);
}, []);
// Example of a POST request
const [user, setUser] = useState({});
const newUser = {
firstName: "John",
lastName: "Doe",
};
useEffect(() => {
useFetch.post(url, newUser, setUser);
}, []);
If you find bugs or have suggestions for improvements, please open an issue or submit a pull request.
useFetch
is licensed under the MIT License. See the LICENSE file for more information.