Part 8 - Queries for Interactions
This is part 8 in this series
This part is based on Queries for Interactions | Relay
Outline:
- Implement
resolve_nodes
method for all classes that extend Node interface in our schema - Add
node
field to our Query type - Copy PosterDetailsHovercardContents component from relay-examples/newsfeed/future at main ยท relayjs/relay-examples to client side
- Load data for the hover card on hover
Implements resolve_nodes
In the Query Variables section, we need to use a new field node
to fetch the current poster information.
The node field is a top-level field in Relay that lets us fetch any graph node given its unique ID. We need to implement support for that.
Commit: https://github.com/tuan/newsfeed-demo-app/commit/e3989966ef0c6596ed564ae177eb5ac51c4be064
The resolve_nodes
method signature is defined on this page.
@classmethod
def resolve_nodes(
cls,
*,
info: Info,
node_ids: Iterable[str],
required: bool = False,
)
The required changes are pretty easy but testing is a bit tricky. Since Relay requires each node to have a globally unique id, Strawberry automatically generates an id using this format: base64("{type_name}:{internal_id}")
.
Here’s one example id that you can use to test the node
field directly using GraphiQL: T3JnYW5pemF0aW9uOjc=
Show hardcoded poster id
After making the changes one the client side as suggested by the Relay tutorial, you should have the hovercard show up on hover
Note: the type annotation used in Relay examples seem wrong. Check out this commit if you have trouble figuring out the typing: https://github.com/tuan/newsfeed-demo-app/commit/4a880a4759e6e1010f181f48b313f279f65b16e0
Passing poster id argument to lazy query
The hover card currently shows a hardcoded poster. Follow the next steps in Relay tutorials to pass a dynamic poster id to the hovercard component.
The change is straigtforward, but you need to adjust it a bit to make it work with Strawberry. Recall that Strawberry auto-generates the node ID, this Id is a custom GraphQL scalar type called GlobalID
instead of ID
.
So when you define the $id
parameter for PosterDetailsHovercardContentsQuery
, use GlobalID
as the type instead of ID
.
export const PosterDetailsHovercardContentsQuery = graphql`
query PosterDetailsHovercardContentsQuery($posterId: GlobalID!) {
node(id: $posterId) {
... on Actor {
...PosterDetailsHovercardContentsBodyFragment
}
}
}
`;
Use Preloaded query
I really like this section in Relay tutorial https://relay.dev/docs/tutorial/queries-2/#preloaded-queries. Using preloaded queries is a great way to improve your app performance. People say Relay is a opinionated framework, but its opinions are great ones. Sometimes it feels like cheating when a great opinion (or practice) that is already made for you, so you can just focus on being productive … with great results!
Commit: https://github.com/tuan/newsfeed-demo-app/commit/48dacd4f649829c7bc2bc73dc5af563799797a45