3

I´m using Relay Modern to build my component and I want to pass a varible to the fragment so that it can be used as a GraphQL argument on my query.

Here is the code I´m using:

class Test extends Component {
    static propTypes = {
       userId: PropTypes.string.isRequired
    }

    render = () => {

        return (

            <p>User Id: {this.props.userId}</p>
            <p>User name: {this.props.viewer.name}
        );
    }
}

export default createFragmentContainer(
    Test,
    graphql`
        fragment Test_viewer on Viewer {
            user(id: $userId) { <<=== The $userId must be the this.props.userId passed
                id
                name
            }
        }
    `
);

When issuing the query GraphQL server returns error saying Variable \"$userId\" is not defined by operation \"UserQuery\".".

My query in the parent component:

const UserQuery = graphql` 

  query AdminQuery {
    viewer {
      ...Test_viewer
    }
  }
`

How can I make the code above work ?

Mendes
  • 17,489
  • 35
  • 150
  • 263

1 Answers1

0

You need to pass your variable at the query level:

const UserQuery = graphql` 
  query AdminQuery($userId: ID!) {
    viewer {
      ...Test_viewer
    }
  }
`;

When using this query on a <QueryRenderer /> element, you will also pass the variables as prop:

<QueryRenderer
  query={UserQuery}
  variables={{
    userId: 'USER_ID',
  }}
  // ... others props
/>
yachaka
  • 5,429
  • 1
  • 23
  • 35