UseFetch hook for react js.
adelchms96
Posted on July 31, 2020
hello guys, will show you a custom hook for handling async call.
useFetch
hook take a callback
as first argument and callback
params for rest arguments.
here it's:
const useFetch = (cb, ...params) => {
const isMounted = useRef();
const [response, setResponse] = useState();
const [loading, setLoading] = useState(false);
//const [error, setError] = useState();
return {
response,
loading,
isMounted,
reset: () => setResponse(),
fetch: async (reload = false) => {
try {
isMounted.current = true;
if (!response || reload) setLoading(true);
const data = await cb(...params);
if (isMounted.cuurent) {
if (data) setResponse(data)
}
} catch (error) {
errorNotification(error); // do something with the error
// or u can add setError(error)
}
finally{
setLoading(false);
}
}
};
};
Usage:
const UserProfile = ({ id }) => {
const { response, loading, fetch, isMounted } = useFetch(getUserProfile, id);
useEffect(() => {
fetch();
return () => {
isMounted.current = false;
};
}, []);
return (
<>{loading ? <p>Loading...</p> : response && <p>{response.userName}</p>}</>
);
};
Note: isMounted
is used to detect component unmount
for not firing unnecessary state update.
hope you like it,thanks.
๐ ๐ช ๐
๐ฉ
adelchms96
Posted on July 31, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
react How to build type-enforced UI components in React Native using @shopify/restyle
November 28, 2024
react Double the Talk, Double the Recording: Capturing Both Sides in Interpreted Zoom Meetings
November 27, 2024