Skip to content

Instantly share code, notes, and snippets.

@Ericnr
Created May 7, 2021 16:43
Show Gist options
  • Save Ericnr/eacfbec50f139bb3627e59a5a2fee69e to your computer and use it in GitHub Desktop.
Save Ericnr/eacfbec50f139bb3627e59a5a2fee69e to your computer and use it in GitHub Desktop.
useLazyFragment example
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