facebook / facebook/relay

Derived Fields - must specify parents fields in query in order to work

Open
#4,943 6 comments 0 reactions 0 assignees View on GitHub
shared with relay team
Dominant language
Rust
Stars
19k
Forks
1.9k
PR merge metrics
No merged PRs in 30d

Description

Hello,

I'm trying the new feature of [derived fields](https://relay.dev/docs/guides/relay-resolvers/derived-fields/). This approach sounds great to replicate the notion of Redux's selectors and have a computed field from server data.

**The struggle:**
There is no example of how to use a "derived field" in a query. My initial assumption was: "when we specify a derived field in a query, the dependent fields in root fragment are indirectly requested" but it's not the case.

Example:
```tsx
import {readFragment} from 'relay-runtime';

/**
* @RelayResolver User.fullName: String
* @rootFragment UserFullNameFragment
*/
export function fullName(key: UserFullNameFragment$key): string {
const user = readFragment(graphql`
fragment UserFullNameFragment on User {
firstName
lastName
}
`, key);
return `${user.firstName} ${user.lastName}`;
}

// in query
graphql`
query myQuery {
viewer {
# myAccount is of type User
myAccount {
# we also need to specify firstName and lastName in order to work ! Or we need spreading the fragment UserFullNameFragment here.
fullName
}
}
}
`
```

Am I right on this behavior ? **If it's the case, is it possible for relay to inject these fields by itself or maybe to throw an error at compilation** ?

It can be error prone to request this derived field and get a null value without any clue on what's going on. I have wasted many hours understanding this subtlety.

Contributor guide

Open the contributing guide

Research direction

Start with the linked derived-fields guide and the UserFullNameFragment/readFragment example in the issue. Reproduce the query with and without firstName and lastName, then inspect the relevant Relay resolver and compiler documentation or tests if they are located. Done should be a documented, validated behavior with either a clear diagnostic or an agreed field-injection design.

Written by the indexing model from the issue text.

Assessment

Tech stack
graphql, typescript
Domain
api, developer-experience, frontend
Issue type
Feature
Difficulty
5/5
Estimated time
Over a week
Activity status
Stale
Clarity
Needs clarification
Newbie friendliness
25/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.