Skip to content

Instantly share code, notes, and snippets.

@sharjeel619
Last active July 22, 2021 13:15
Show Gist options
  • Save sharjeel619/152a65edc6cf42c622a6d43640701c66 to your computer and use it in GitHub Desktop.
Save sharjeel619/152a65edc6cf42c622a6d43640701c66 to your computer and use it in GitHub Desktop.
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} />
</>
);
@sharjeel619
Copy link
Author

  • 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