0
0
GraphQLquery~5 mins

Parent (root) argument in GraphQL

Choose your learning style9 modes available
Introduction

The parent (root) argument helps you access data from the previous level when fetching nested information in GraphQL.

When you want to get related data inside a nested query.
When resolving fields that depend on data from the parent object.
When building a list of items connected to a main item.
When you need to fetch details based on the current object in the query.
Syntax
GraphQL
fieldName(parent, args, context, info) {
  // use parent to get data from the previous level
}

parent is the first argument and holds data from the previous resolver.

You use parent to access fields already fetched before.

Examples
Here, posts resolver uses parent.id to get posts for the user fetched in the user resolver.
GraphQL
user(parent, args, context, info) {
  return getUserById(args.id);
}

posts(parent, args, context, info) {
  return getPostsByUserId(parent.id);
}
The author resolver uses parent.authorId from the book to fetch the author details.
GraphQL
book(parent, args, context, info) {
  return getBookById(args.id);
}
author(parent, args, context, info) {
  return getAuthorById(parent.authorId);
}
Sample Program

This example shows a user with posts. The posts resolver uses parent.id to find posts for that user.

GraphQL
const resolvers = {
  Query: {
    user(parent, args, context, info) {
      return { id: 1, name: 'Alice' };
    }
  },
  User: {
    posts(parent, args, context, info) {
      return [
        { id: 101, title: 'Hello World', userId: parent.id },
        { id: 102, title: 'GraphQL Basics', userId: parent.id }
      ];
    }
  }
};

// Query:
// {
//   user {
//     name
//     posts {
//       title
//     }
//   }
// }
OutputSuccess
Important Notes

The parent argument is often called root or source in some tutorials.

If you are at the top query level, parent is usually undefined or an empty object.

Summary

The parent argument gives access to data from the previous resolver.

It is useful for nested queries to connect related data.

Always remember parent is the first argument in resolver functions.