Skip to content

Instantly share code, notes, and snippets.

@kseikyo
Created August 2, 2021 16:43
Show Gist options
  • Save kseikyo/c8b194a991dd944e0af821cb2c46002a to your computer and use it in GitHub Desktop.
Save kseikyo/c8b194a991dd944e0af821cb2c46002a to your computer and use it in GitHub Desktop.
/**
* Issues:
* 1. Suspense does not have a fallback.
* 2. As the data is related, one Suspense should wrap them all.
* 3. Suspense is not wrapping the data fetching component.
* 4. There is no ErrorBoundary to handle a failing request.
*/
import { Suspense, useState, useEffect, ErrorBoundary } from 'react';
// Abstracting the data fetching into a custom hook
const useUserProfileById = userId => {
const [data, setData] = useState();
useEffect(() => {
fetchUserProfile(userId).then((profile) => setData(profile));
}, [userId, setData]);
return {data};
}
// Use the custom hook where the UI component is CALLED.
const FulUserProfile = ({ userId }) => {
const { data: user } = useUserProfileById(userId);
return (
<UserProfile user={user} />
);
};
const UserProfile = ({ user }) => {
return (
<>
<h1>{user.name}</h1>
<h2>{user.email}</h2>
</>
);
};
// Adding an ErrorBoundary and Suspense that wraps this context
const UserProfileList = () => (
<ErrorBoundary error="something went wrong :(">
<Suspense fallback={<h1>Loading users...</h1>}>
<FulUserProfile userId={1} />
<FulUserProfile userId={2} />
<FulUserProfile userId={3} />
</Suspense>
</ErrorBoundary>
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment