Created
September 27, 2021 12:29
-
-
Save avoajaugochukwu/128eb65ae1113c4e262d5a65c05df873 to your computer and use it in GitHub Desktop.
This file contains 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
/* | |
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: '[email protected]'}, | |
{id: 2, name: 'James', email: '[email protected]'}, | |
{id: 3, name: 'Jungen', email: '[email protected]'} | |
] | |
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