GraphQL / Relay - do all tables need to be queried in main QueryRenderer?

230 Views Asked by At

I'm new to GraphQL and Relay and I'm struggling with queries, fragments, ...spreads & passing props. I think I'm unnecessarily passing props down through many, many components. I want to learn how to teleport my data objects from the QueryRenderer to deeply nested components, skipping all the ancestor components.

Suppose I have a component structure like this. I need a list of emojis from the 'emoji' table inside EmojisList component which is deep in the app. I'm not sure where to spread or pass props or when to ask for the actual scalars.

<MainApp>
  <QueryRenderer 
    environment={environment}
    query={graphql`
        query MainAppQuery {
        currentPerson { // current user
            ...Timeline_currentPerson
        }
        allEmojis {
            ...ReactionBar_emojisList
          }
        }
    `}
  />
  <Timeline currentPerson={props.currentPerson}>
    <PostList>
      <Post>
        <ReactionBar>
          <EmojisList>
            // I need this list
            export default createFragmentContainer(ReactionBar, {
              emojisList: graphql`
                fragment ReactionBar_emojisList on EmojisConnection @relay(plural: true) {
                  edges {
                    node {
                      name
                      rowId
                    }
                  }
                }
              `,
            });      
          </EmojisList>
        </ReactionBar>
      </Post>
    </PostList>
  </Timeline>
</MainApp>

Console error

1

There are 1 best solutions below

1
On

You can use Fragment Container

Wrap <EmojiList /> Component with createFragmentContainer HOC then it will grab all of the data you need that you have fetched at the root from QueryRenderer .

The data will be accessible as props inside the component

// EmojisList.js
import {createFragmentContainer, graphql} from 'react-relay';

class EmojisList extends React.Component {/* code */}

// Export a *new* React component that wraps the original `<EmojisList>`.
export default createFragmentContainer(EmojisList, {
  emojisList: graphql`
    fragment EmojisList_emojisList on EmojisConnection {
      edges {
        node {
         name
         rowId
        }
      }
    }
  `,
});