iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Aliases

Aliases rename a field in the response. Use them to query the same field with different arguments in one round trip, or to flatten nested data.

Aliases for parallel queries and clean shapes

EXAMPLE
# 1) Same field, different arguments
query DashboardCounts {
    pending:   posts(status: PENDING)   { totalCount }
    published: posts(status: PUBLISHED) { totalCount }
    archived:  posts(status: ARCHIVED)  { totalCount }
}

# Response shape — keys are the aliases, not the field name
# { data: { pending: { totalCount: 5 }, published: { totalCount: 42 }, archived: { totalCount: 17 } } }

# 2) Compose multiple fetches in one round trip
query Profile($id: ID!) {
    user(id: $id) {
        id
        name
        recentPosts: posts(first: 5, orderBy: CREATED_DESC) {
            edges { node { id title } }
        }
        popularPosts: posts(first: 5, orderBy: VIEWS_DESC) {
            edges { node { id title views } }
        }
        followers:  followCount(role: FOLLOWER)
        following:  followCount(role: FOLLOWING)
    }
}

# 3) Rename a field for clean front-end shape
query Header($uid: ID!) {
    me: user(id: $uid) {       # data.me reads natural
        avatar: profilePictureUrl
        unread: notificationCount(unreadOnly: true)
    }
}

# 4) Avoid alias clashes when using fragments across multiple parents
fragment Counts on User {
    posts:    postCount
    comments: commentCount
}
query Both($a: ID!, $b: ID!) {
    alice: user(id: $a) { ...Counts }
    bob:   user(id: $b) { ...Counts }
}

# 5) Apollo Client — alias works as the field name on the data object
const { data } = useQuery(DashboardCounts);
console.log(data.pending.totalCount);
console.log(data.published.totalCount);

Why it matters

Aliases let you batch related fetches into ONE query. Same network round trip, same auth check, same caching key — the unlocking technique for dashboard-style screens.

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
{ ada: user(id: 1) { name } linus: user(id: 2) { name } }
Try it Yourself »

Discussion

Loading…