From 3191e3da544c833daeabbfced5efb9568d4bb4ae Mon Sep 17 00:00:00 2001 From: e560248 Date: Mon, 7 Apr 2025 12:01:14 +0200 Subject: [PATCH] useEffect example 2: loading users from API --- react-advanced-tag1/src/App.tsx | 6 +- .../src/components/exercises/UserEffect.tsx | 61 +++++++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) create mode 100644 react-advanced-tag1/src/components/exercises/UserEffect.tsx diff --git a/react-advanced-tag1/src/App.tsx b/react-advanced-tag1/src/App.tsx index d6a545e..443c54e 100644 --- a/react-advanced-tag1/src/App.tsx +++ b/react-advanced-tag1/src/App.tsx @@ -1,5 +1,6 @@ import './App.css' -import EffectExercises from './components/exercises/EffectExercises' +// import EffectExercises from './components/exercises/EffectExercises' +import UserEffect from './components/exercises/UserEffect' import Heading from './components/globals/Heading' import MainLayout from './layouts/MainLayout' @@ -7,7 +8,8 @@ function App() { return - + {/* */} + } diff --git a/react-advanced-tag1/src/components/exercises/UserEffect.tsx b/react-advanced-tag1/src/components/exercises/UserEffect.tsx new file mode 100644 index 0000000..ee4740d --- /dev/null +++ b/react-advanced-tag1/src/components/exercises/UserEffect.tsx @@ -0,0 +1,61 @@ +import { useEffect, useState } from "react"; + +interface User { + id: number; + name: string; + email: string; + website: string; +} + +export default function UserEffect() { + const [user, setUser] = useState(); + const [userId, setUserId] = useState(0); + const [loading, setLoading] = useState(false); + + useEffect(() => { + console.log("UserEffect mounted"); + + if (userId === 0) { + return; + } + + setLoading(true); + + // Using AbortController to cancel the fetch request if the component unmounts + // or if the userId changes before the fetch completes + const controller = new AbortController(); + const signal = controller.signal; + + fetch(`https://jsonplaceholder.typicode.com/users/${userId}`, {signal: signal}).then(response => { + if (!response.ok) { + throw new Error("Network response was not ok"); + } + return response.json(); + }).then(data => { + setUser(data); + setLoading(false); + }).catch(error => { + console.error("There was a problem with the fetch operation:", error); + }); + return () => { + console.log("UserEffect unmounted"); + // Cleanup function to abort the fetch request if the component unmounts + // or if the userId changes before the fetch completes + controller.abort('Fetch aborted'); + } + }, [userId]); + + return ( +
+

users Effect Exercise

+ + {userId === 0 &&

Please select a user

} + {loading || userId === 0 ?

Loading...

:

[{user?.id}] {user?.name}: {user?.website}

} + + + + + +
+ ) +} \ No newline at end of file