0

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

Kirk Ross
  • 6,413
  • 13
  • 61
  • 104

1 Answers1

0

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
        }
      }
    }
  `,
});
  • Thanks. Yes, I actually had it wrapped in a createFragmentContainer, but forgot to add it. (added to OP). I keep getting this error: createFragmentSpecResolver: Expected prop emojisList` to be supplied to Relay(ReactionBar), but got undefined.` The GraphiQL query for getting all emojis is allEmojis {edges { node { scalars }}} – Kirk Ross Jan 24 '21 at 20:55