Skip to content

Instantly share code, notes, and snippets.

@avoajaugochukwu
Created September 27, 2021 12:29
Show Gist options
  • Save avoajaugochukwu/128eb65ae1113c4e262d5a65c05df873 to your computer and use it in GitHub Desktop.
Save avoajaugochukwu/128eb65ae1113c4e262d5a65c05df873 to your computer and use it in GitHub Desktop.
/*
Time taken: 10 minutes
What I did.
1). I imported 'React'
2). I created a small user array with objects
3). I built out a Promise function for fetchUserProfile that resolves (finds an id match) or rejects (no id match found)
4). I added a fallback to React Suspense to display while data is fetching and component rendering is paused
The fallback is not showing, because data is in the file. If an API is used the fallback will show and not render the component
until data is available
*/
import React, { Suspense, useState, useEffect } from 'react';
const userRecords = [
{id: 1, name: 'John', email: 'john@email.com'},
{id: 2, name: 'James', email: 'james@email.com'},
{id: 3, name: 'Jungen', email: 'jungen@email.com'}
]
const SuspensefulUserProfile = ({ userId }) => {
const [data, setData] = useState({});
useEffect(() => {
fetchUserProfile(userId).then((profile) => setData(profile));
}, [userId, setData])
const fetchUserProfile = (userId) => {
return new Promise((resolve, reject) => {
const findUser = userRecords.filter(userRecord => userRecord.id === userId)
if (findUser) {
resolve(...findUser)
} else {
reject('Error fetching user data')
}
})
}
return (
<Suspense fallback={<h1>Loading profile...</h1>}>
<UserProfile data={data} />
</Suspense>
);
};
const UserProfile = ({ data }) => {
return (
<>
<h1>{data.name}</h1>
<h2>{data.email}</h2>
</>
);
};
const UserProfileList = () => (
<>
<SuspensefulUserProfile userId={1} />
<SuspensefulUserProfile userId={2} />
<SuspensefulUserProfile userId={3} />
</>
);
//<UserProfileList />
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment