Pass variables to fragment container in relay modern

前端 未结 1 685
一生所求
一生所求 2020-12-31 14:18

I\'m using Relay Modern (compat). I have a fragment that contains a field that has one argument, but I can\'t find a way of passing the variable value from the parent compon

1条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-31 14:36

    Using @argumentDefinitions and @arguments directives seems to be the way to go. In relay versions before 1.4.0 graphql.experimental had to be used instead of graphql.

    In the fragment definition:

    const fragments = {
      employee: graphql`
        fragment MyFragmentComponent_employee on Employee
        @argumentDefinitions(includeOvertime: { type: "Boolean", defaultValue: false }) {
          hoursWorked(includeOvertime: $includeOvertime)
          dob
          fullName
          id
        }
      `,
    }
    

    If you want the argument to be required:

    @argumentDefinitions(includeOvertime: { type: "Boolean!" })
    

    In the parent component you should specify the arguments for the fragment like this:

    const query = graphql`
      query MyRootComponentQuery($employeeId: String!, $includeOvertime: Boolean) {
        employee(id: $employeeId) {
          fullName
          ...MyFragmentComponent_employee @arguments(includeOvertime: $includeOvertime)
        }
      }
    `
    

    In this page in the official relay docs there is an example of directives for defining/passing arguments.

    UPDATE:

    Since relay version 1.4.0 graphql.experimental was deprecated and now all the features are supported by the regular graphql tag.

    UPDATE:

    In relay version 1.5.0 graphql.experimental was removed.

    0 讨论(0)
提交回复
热议问题