Last active
July 22, 2021 13:15
-
-
Save sharjeel619/152a65edc6cf42c622a6d43640701c66 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import "./styles.css"; | |
import { Suspense, useState, useEffect, Component } from "react"; | |
class ErrorBoundary extends Component { | |
constructor(props) { | |
super(props); | |
this.state = { hasError: false }; | |
} | |
static getDerivedStateFromError(error) { | |
// Update state so the next render will show the fallback UI. | |
return { hasError: true }; | |
} | |
componentDidCatch(error, errorInfo) { | |
// You can also log the error to an error reporting service | |
console.error(error); | |
console.error(errorInfo); | |
} | |
render() { | |
if (this.state.hasError) { | |
return ( | |
<div className="container"> | |
<div className="row mt-2"> | |
<div className="col-8"> | |
<div className="alert alert-secondary text-center"> | |
Error in UserProfile component | |
</div> | |
</div> | |
</div> | |
</div> | |
); | |
} | |
return this.props.children; | |
} | |
} | |
export default function App() { | |
return ( | |
<div className="App"> | |
<h1>Hello CodeSandbox</h1> | |
<h2>Start editing to see some magic happen!</h2> | |
<UserProfileList /> | |
</div> | |
); | |
} | |
const fetchUserProfile = (id) => { | |
return fetch(`https://jsonplaceholder.typicode.com/users/${id}`).then((res) => | |
res.json() | |
); | |
}; | |
const SuspensefulUserProfile = ({ userId }) => { | |
const [data, setData] = useState({}); | |
useEffect(() => { | |
fetchUserProfile(userId).then((profile) => { | |
setData(profile); | |
}); | |
}, [userId]); | |
return ( | |
<ErrorBoundary> | |
<Suspense fallback={<div>Loading...</div>}> | |
<UserProfile data={data} /> | |
</Suspense> | |
</ErrorBoundary> | |
); | |
}; | |
const UserProfile = ({ data }) => { | |
return ( | |
<> | |
<h1>{data?.name}</h1> | |
<h2>{data?.email}</h2> | |
</> | |
); | |
}; | |
const UserProfileList = () => ( | |
<> | |
<SuspensefulUserProfile userId={1} /> | |
<SuspensefulUserProfile userId={2} /> | |
<SuspensefulUserProfile userId={3} /> | |
</> | |
); |
Author
sharjeel619
commented
Jul 22, 2021
- setData not needed as dependency in useEffect hook.
- fallback attribute in Suspense can be useful if the API is still in fetching state.
- ErrorBoundary can help prevent app crash if there is an error in UserProfile component
- id argument in fetchUserProfile API call has no type check
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment