knowbody / reason-relay

Use Relay with ReasonML.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

reason-relay

Use Relay with ReasonML.

Getting started

Check out the documentation (work in progress) here.

What it looks like

Your components define what data they need through [%relay.fragment].

/* Avatar.re */
module UserFragment = [%relay.fragment
  {|
  fragment Avatar_user on User {
    firstName
    lastName
    avatarUrl
  }
|}
];

[@react.component]
let make = (~user) => {
  let userData = UserFragment.use(user);

  <img
    className="avatar"
    src={userData.avatarUrl}
    alt={userData.firstName ++ " " userData.lastName}
  />;
};

Fragments can include other fragments. This allows you to break your UI into encapsulated components defining their own data demands.

Hooks to use your fragments are autogenerated for you. The hook needs a fragment reference from the GraphQL object where it was spread. Any object with one or more fragments spread on it will have a getFragmentRefs() function. Use that to get all fragment references for that object, and then pass that to the fragment hook.

Avatar_user is spread right on the fragment, so we use userData.getFragmentRefs() to get an object with the needed fragment references and pass that to the <Avatar /> component. The <Avatar /> component then uses that to get its data.

/* UserProfile.re */
module UserFragment = [%relay.fragment
  {|
  fragment UserProfile_user on User {
    firstName
    lastName
    friendCount
    ...Avatar_user
  }
|}
];

[@react.component]
let make = (~user) => {
  let userData = UserFragment.use(user);

  <div>
    <Avatar user={userData.getFragmentRefs()} />
    <h1> {React.string(userData.firstName ++ " " ++ userData.lastName)} </h1>
    <div>
      <p>
        {React.string(
           userData.firstName
           ++ " has "
           ++ userData.friendCount->string_of_int
           ++ " friends.",
         )}
      </p>
    </div>
  </div>;
};

Finally, you make a query using [%relay.query] and include the fragments needed to render the entire tree of components.

/* Dashboard.re */
module Query = [%relay.query
  {|
  query DashboardQuery {
    me {
      ...UserProfile_user
    }
  }
|}
];

[@react.component]
let make = () => {
  let queryData = Query.use(~variables=(), ());

  <div> <UserProfile user={queryData.me.getFragmentRefs()} /> </div>;
};

Examples

About

Use Relay with ReasonML.


Languages

Language:Reason 66.7%Language:JavaScript 18.6%Language:TypeScript 13.7%Language:Shell 0.7%Language:HTML 0.2%Language:C++ 0.2%