diff --git a/Refactored.jsx b/Refactored.jsx new file mode 100644 index 0000000..5900bed --- /dev/null +++ b/Refactored.jsx @@ -0,0 +1,58 @@ +import React, { useState, useEffect, useRef } from 'react'; + +function UserProfile({ userId }) { + const [user, setUser] = useState(null); + const [loading, setLoading] = useState(true); + const [error, setError] = useState(null); + const abortControllerRef = useRef(null); + + const fetchUser = () => { + if (abortControllerRef.current) { + abortControllerRef.current.abort(); + } + abortControllerRef.current = new AbortController(); + + setLoading(true); + setError(null); + + fetch(`https://api.example.com/users/${userId}`, { + signal: abortControllerRef.current.signal, + }) + .then((response) => response.json()) + .then((data) => { + setUser(data); + setLoading(false); + }) + .catch((err) => { + if (err.name !== 'AbortError') { + setError(err.message); + setLoading(false); + } + }); + }; + + // componentDidMount + componentDidUpdate for userId changes + useEffect(() => { + fetchUser(); + + // Cleanup function similar to componentWillUnmount + return () => { + if (abortControllerRef.current) { + abortControllerRef.current.abort(); + } + }; + }, [userId]); // re-run when userId changes + + if (loading) return
Loading user data...
; + if (error) returnError: {error}
; + + return ( +Email: {user.email}
+ +Loading user data...
; + if (error) returnError: {error}
; + + return ( +Email: {user.email}
+ +