Created
May 7, 2021 16:43
-
-
Save Ericnr/eacfbec50f139bb3627e59a5a2fee69e to your computer and use it in GitHub Desktop.
useLazyFragment example
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
const FriendsList = props => { | |
const data = useFragment( | |
graphql` | |
fragment FriendsList_person on Person { | |
friends { | |
id | |
name | |
...FriendDetails_friend | |
} | |
} | |
`, | |
props.person | |
); | |
const [expandedFriendIds, setExpanded] = useState([]); | |
const toggleExpanded = friendId => { | |
/* ... */ | |
}; | |
return data.friends.map(friend => ( | |
<div key={friend.id}> | |
<b onClick={() => toggleExpanded(friend.id)}>{friend.name}</b> | |
{expandedFriendIds.includes(friend.id) && ( | |
<Suspense fallback="fetching friend details"> | |
<FriendDetails friend={friend} /> | |
</Suspense> | |
)} | |
</div> | |
)); | |
}; | |
// FriendDetails is a conditionally rendered component | |
// therefore we don't need to load its data until the user clicks to expand it | |
const FriendsDetails = props => { | |
const data = useLazyFragment( | |
graphql` | |
fragment FriendDetails_friend on Friend { | |
id | |
name | |
age | |
nickname | |
} | |
`, | |
props.friend | |
); | |
return <div>{/* render details */}</div>; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment