@supunlakmal/hooks
Version:
A collection of reusable React hooks
46 lines • 1.77 kB
JavaScript
import { useState, useEffect, useRef } from 'react';
export const useFetch = (url, options) => {
const [state, setState] = useState({
data: null,
loading: false,
error: null,
});
// Use useRef to keep track of the options object to prevent infinite loops
// if a new options object is passed on every render.
// A simple JSON.stringify can be used for deep comparison if needed, but be cautious of performance.
const optionsRef = useRef(options);
useEffect(() => {
optionsRef.current = options;
}, [options]);
useEffect(() => {
// Only fetch if the URL is provided
if (!url) {
setState({ data: null, loading: false, error: null });
return;
}
const fetchData = async () => {
setState({ data: null, loading: true, error: null });
try {
const response = await fetch(url, optionsRef.current);
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const result = await response.json();
setState({ data: result, loading: false, error: null });
}
catch (error) {
setState({
data: null,
loading: false,
error: error instanceof Error
? error
: new Error('An unknown error occurred'),
});
}
};
fetchData();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [url]); // Re-run effect only if URL changes. Options dependency managed via ref.
return state;
};
//# sourceMappingURL=useFetch.js.map