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