useEffect example 2: loading users from API

This commit is contained in:
e560248
2025-04-07 12:01:14 +02:00
parent c9f72a8902
commit 3191e3da54
2 changed files with 65 additions and 2 deletions

View File

@@ -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 <MainLayout>
<Heading />
<EffectExercises />
{/* <EffectExercises /> */}
<UserEffect />
</MainLayout>
}

View File

@@ -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<User>();
const [userId, setUserId] = useState<number>(0);
const [loading, setLoading] = useState<boolean>(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 (
<section>
<h2>users Effect Exercise</h2>
{userId === 0 && <p>Please select a user</p>}
{loading || userId === 0 ? <p>Loading...</p> : <p>[{user?.id}] {user?.name}: {user?.website}</p>}
<button onClick={() => setUserId(1)} style={{padding: 10, border: '1px solid gray'}}>User 1</button>
<button onClick={() => setUserId(2)} style={{padding: 10, border: '1px solid gray'}}>User 2</button>
<button onClick={() => setUserId(3)} style={{padding: 10, border: '1px solid gray'}}>User 3</button>
<button onClick={() => setUserId(4)} style={{padding: 10, border: '1px solid gray'}}>User 4</button>
</section>
)
}