Relay (GraphQL)

https://relay.dev/docs/guided-tour/rendering/fragments/

How does Relay know which endpoint to talk to?

The useLazyLoadQuery hook fetches and returns the data. It takes two arguments:

  • The GraphQL query that we defined before.
  • Variables that are passed to the server with the query. This query doesn’t declare any variables, so it’s an empty object.

Fragments

The main building block for declaring data dependencies for React Components in Relay are GraphQL Fragments.

Fragments are a selection of fields on a GraphQL type:

fragment UserFragment on User {
  name
  age
  profile_picture(scale: 2) {
    uri
  }
}

In order to render the data for a fragment, you can use the useFragment Hook:

import type {UserComponent_user$key} from 'UserComponent_user.graphql';
 
const React = require('React');
 
const {graphql, useFragment} = require('react-relay');
 
type Props = {
  user: UserComponent_user$key,
};
 
function UserComponent(props: Props) {
  const data = useFragment(
    graphql`
      fragment UserComponent_user on User {
        name
        profile_picture(scale: 2) {
          uri
        }
      }
    `,
    props.user,
  );
 
  return (
    <>
      <h1>{data.name}</h1>
      <div>
        <img src={data.profile_picture?.uri} />
      </div>
    </>
  );
}
 
module.exports = UserComponent;