reactjsgraphqlrelayrelaymodern

Multiple Relay fragments in one React component?


This is example from the docs. The problem is, what if I also need some other data in my TodoItem component that is completely on a different location in the data graph and can't come through Todo->TodoItem chain.

class TodoItem extends React.Component {
  render() {
    const item = this.props.data;

  }
}
module.exports = createFragmentContainer(
  TodoItem,
  graphql`
    fragment TodoItem on Todo {
      text
      isComplete
    }
  `,
);

It seems that Relay/GraphQL demands that the view is composed in the same hierarchy as the data model. Is there a way for a component to access other fragments? I don't know, something like this:

module.exports = createFragmentContainer(
  TodoItem,
  graphql`
    fragment TodoItem on Todo {
      text
      isComplete
    }
  `,
  graphql`
    fragment FriendItem on Friends {
      name
    }
  `,
);

Solution

  • I'm not sure if that's what you want, (I'm also just starting with relay) but you can specify different fragments using keys in the createFragmentContainer function:

    Fragmentcontainer:

    export default createFragmentContainer(TodoItem, {
      todo: graphql`
        fragment TodoItem_todo on Todo {
          text
          isComplete
        }
      `,
      friend: graphql`
        fragment FriendItem_friend on Friends {
          name
        }
      `,
    });
    

    And then in your queryRenderer something like this:

    query={graphql`
        query AppQuery {
            todos {
                ...TodoItem_todo
            }
            friends {
                ...FriendItem_friend
            }
        }
    `}