Saturday, October 15, 2022

Fetching JSON data from API with useEffect

import { useEffect, useState } from 'react';

export default function useFetch(url) {
const [data, setData] = useState(false);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(false);
useEffect(() => {
setLoading(true);
fetch(url, {
method: 'GET',
mode: 'cors',
dataType: 'json',
headers: {
'Content-Type': 'application/json',
Accept: 'application/json',
},
})
.then((res) => {
if (!res.ok) {
throw new Error(
`HTTP ${res.status} ${res.statusText}. Fetch ${res.url}`
);
}
return res.json();
})
.then((obj) => {
setData(obj);
console.log(`Fetched ${url}`);
})
.catch((err) => {
setError(err);
console.log(err); // throw new Error || err.message
})
.finally(() => {
setLoading(false);
});
}, [url]);

return { data, error, loading };
}

https://www.codementor.io/@mohammedelhossinyriaad/how-the-useeffect-react-hook-work-1cq3g0g8bd

https://www.smashingmagazine.com/2020/07/custom-react-hook-fetch-cache-data/

https://www.robinwieruch.de/react-hooks-fetch-data/

https://dev.to/shaedrizwan/building-custom-hooks-in-react-to-fetch-data-4ig6

https://www.developerway.com/posts/how-to-fetch-data-in-react

https://use-http.com/#/

No comments:

Post a Comment