Skip to content

Commit

Permalink
Merge pull request #31 from Code-the-Dream-School/FetchHook
Browse files Browse the repository at this point in the history
Fetch Hook Created
  • Loading branch information
ValeriGuerrero authored Dec 11, 2024
2 parents 80589eb + b7df846 commit d1828f4
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 14 deletions.
21 changes: 7 additions & 14 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 37 additions & 0 deletions src/hooks/useFetch.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { useState, useEffect } from 'react';

const useFetch = (url) => {
const [isLoading, setIsLoading] = useState(true);
const [isError, setIsError] = useState(false);
// change state value
const [data, setData] = useState(null);

useEffect(() => {
// change name
const fetchData = async () => {
try {
const resp = await fetch(url);

if (!resp.ok) {
setIsError(true);
setIsLoading(false);
return;
}
// change to response
const response = await resp.json();
setData(response);
} catch (error) {
setIsError(true);
// console.log(error);
}
// hide loading
setIsLoading(false);
};
// invoke fetch data
fetchData();
}, []);

return { isLoading, isError, data };
};

export default useFetch;

0 comments on commit d1828f4

Please sign in to comment.