custom hook useFetch
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
import './App.css'
|
||||
// import EffectExercises from './components/exercises/EffectExercises'
|
||||
import UserEffect from './components/exercises/UserEffect'
|
||||
import { UserOverview } from './components/exercises/UserOverview'
|
||||
import Heading from './components/globals/Heading'
|
||||
import MainLayout from './layouts/MainLayout'
|
||||
|
||||
@@ -10,6 +11,7 @@ function App() {
|
||||
<Heading />
|
||||
{/* <EffectExercises /> */}
|
||||
<UserEffect />
|
||||
<UserOverview />
|
||||
</MainLayout>
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { useFetch } from "../../hooks/useFetch";
|
||||
|
||||
export function UserOverview() {
|
||||
const {data, loading, error} = useFetch("https://jsonplaceholder.typicode.com/users");
|
||||
|
||||
if (error) {
|
||||
return <p>Error: {error}</p>;
|
||||
}
|
||||
if (loading) {
|
||||
return <p>Loading...</p>;
|
||||
}
|
||||
if (!data) {
|
||||
return <p>No data available</p>;
|
||||
}
|
||||
return (
|
||||
<div>
|
||||
<h2>User Overview</h2>
|
||||
<ul>
|
||||
{data.map((user: { id: number; name: string; email: string; website: string }) => (
|
||||
<li key={user.id}>
|
||||
<strong>{user.name}</strong> ({user.email}) - {user.website}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>Total Users: {data.length}</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
49
react-advanced-tag1/src/hooks/useFetch.ts
Normal file
49
react-advanced-tag1/src/hooks/useFetch.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
interface User {
|
||||
id: number;
|
||||
name: string;
|
||||
email: string;
|
||||
website: string;
|
||||
}
|
||||
|
||||
export function useFetch(url: string) {
|
||||
const [data, setData] = useState<User[] | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
// alternativ
|
||||
// const [fetchValues, setFetchValues] = useState({
|
||||
// data: null,
|
||||
// loading: true,
|
||||
// error: null,
|
||||
// });
|
||||
|
||||
useEffect(() => {
|
||||
async function fetchData() {
|
||||
try {
|
||||
const response = await fetch(url);
|
||||
if (!response.ok) {
|
||||
setError("Network response was not ok");
|
||||
throw new Error("Network response was not ok");
|
||||
}
|
||||
const data = await response.json();
|
||||
setData(data);
|
||||
setError(null);
|
||||
|
||||
} catch (error) {
|
||||
console.error("Error fetching data:", error);
|
||||
setError("Error fetching data");
|
||||
}
|
||||
finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
fetchData();
|
||||
|
||||
|
||||
}, [url]);
|
||||
|
||||
return { data, loading, error };
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user