0
0
GraphQLquery~30 mins

Fragments for reusable selections in GraphQL - Mini Project: Build & Apply

Choose your learning style9 modes available
Using GraphQL Fragments for Reusable Selections
📖 Scenario: You are building a simple GraphQL query to fetch user information from a social media app. You want to reuse parts of the query to avoid repeating the same fields multiple times.
🎯 Goal: Create a GraphQL fragment named UserInfo that selects the id, name, and email fields from a User type. Then use this fragment in two queries: one to get the current logged-in user and another to get a list of friends.
📋 What You'll Learn
Create a fragment called UserInfo selecting id, name, and email from User.
Write a query called GetCurrentUser that uses the UserInfo fragment to fetch the current user.
Write a query called GetFriends that uses the UserInfo fragment to fetch a list of friends.
💡 Why This Matters
🌍 Real World
In real apps, GraphQL fragments help you avoid repeating the same field lists in many queries, making your code easier to read and update.
💼 Career
Knowing how to use fragments is important for frontend and backend developers working with GraphQL APIs to write efficient and maintainable queries.
Progress0 / 4 steps
1
Create the UserInfo fragment
Write a GraphQL fragment named UserInfo on the User type that selects the fields id, name, and email.
GraphQL
Need a hint?

Use the fragment keyword followed by the fragment name, the on keyword, and the type name. Then list the fields inside curly braces.

2
Write the GetCurrentUser query using the fragment
Write a GraphQL query named GetCurrentUser that fetches the currentUser field and uses the UserInfo fragment to select its fields.
GraphQL
Need a hint?

Use the query keyword with the query name, then select currentUser and spread the fragment inside it with ...UserInfo.

3
Write the GetFriends query using the fragment
Write a GraphQL query named GetFriends that fetches the friends field (a list of users) and uses the UserInfo fragment to select each friend's fields.
GraphQL
Need a hint?

Similar to the previous query, use query GetFriends, select friends, and spread the fragment ...UserInfo inside.

4
Complete the GraphQL document with both queries and the fragment
Ensure the GraphQL document includes the UserInfo fragment, the GetCurrentUser query, and the GetFriends query all together.
GraphQL
Need a hint?

Make sure all parts are included in the same document so you can reuse the fragment in both queries.