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) return

Error: {error}

; + + return ( +
+

{user.name}

+

Email: {user.email}

+ +
+ ); +} + +export default UserProfile; diff --git a/UserProfile.jsx b/UserProfile.jsx new file mode 100644 index 0000000..f99ba74 --- /dev/null +++ b/UserProfile.jsx @@ -0,0 +1,67 @@ +import React, { Component } from 'react'; + +class UserProfile extends Component { + constructor(props) { + super(props); + this.state = { + user: null, + loading: true, + error: null, + }; + this.handleRefresh = this.handleRefresh.bind(this); + } + + componentDidMount() { + this.fetchUser(); + } + + componentDidUpdate(prevProps) { + if (prevProps.userId !== this.props.userId) { + this.fetchUser(); + } + } + + componentWillUnmount() { + // Cleanup if needed (e.g., abort fetch) + if (this.abortController) { + this.abortController.abort(); + } + } + + fetchUser() { + this.abortController = new AbortController(); + this.setState({ loading: true, error: null }); + + fetch(`https://api.example.com/users/${this.props.userId}`, { + signal: this.abortController.signal, + }) + .then((response) => response.json()) + .then((data) => this.setState({ user: data, loading: false })) + .catch((error) => { + if (error.name !== 'AbortError') { + this.setState({ error: error.message, loading: false }); + } + }); + } + + handleRefresh() { + this.fetchUser(); + } + + render() { + const { user, loading, error } = this.state; + + if (loading) return

Loading user data...

; + if (error) return

Error: {error}

; + + return ( +
+

{user.name}

+

Email: {user.email}

+ +
+ ); + } +} + +export default UserProfile;