How to pass graphQL query variable to decorated react component

Does anyone know how to properly react to correctly adding a query variable to apollo? I can get the following code to work if I manually add the book name string instead of passing it in the request variable $name

, but as soon as I add it and try to pass the name variable via an option in propTypes,Invariant Violation: The operation 'data' wrapping 'BookPage' is expecting a variable: 'name' but it was not found in the props passed to 'Apollo(BookPage)'

I pulled the syntax for the decorator directly from the reactQL package , so I know it has a little more syntactic sugar than the other examples, but should it stay true to query?

const query = gql`
  query ($name: String!){
    bookByName(name: $name) {
      id
    }
}
`;

@graphql(query)
class BookPage extends React.PureComponent {
  static propTypes = {
    options: (props) => { return { variables: { name: "Quantum Mechanics"}}},
    data: mergeData({
      book:
        PropTypes.shape({
          id: PropTypes.string.isRequired,
        }),
    }),
  }

  render() {
    const { data } = this.props;
    if (data.loading) {
      return <p>Loading</p>
    }
    const { bookByName } = data;
    const book = bookByName;

    return (
      <p>book.id</p>
    );
  }
}

export default BookPage;

      

+3


source to share


1 answer


The decorator @graphql

has a second parameter where you define the parameters for the request or mutation.

Similar to defining options in config .

So, in your case it might look like this:



const query = gql`
  query ($name: String!){
    bookByName(name: $name) {
      id
    }
}
`;

@graphql(query, {
  options: (ownProps) => ({
    variables: {
      name: ownProps.bookName // ownProps are the props that are added from the parent component
    },
  })})
class BookPage extends React.PureComponent {
  static propTypes = {
    bookName: PropTypes.string.isRequired,
    data: mergeData({
      book:
        PropTypes.shape({
          id: PropTypes.string.isRequired,
        }),
    }),
  }

  render() {
    const { data } = this.props;
    if (data.loading) {
      return <p>Loading</p>
    }
    const { bookByName } = data;
    const book = bookByName;

    return (
      <p>book.id</p>
    );
  }
}

export default BookPage;
      

Run codeHide result


+4


source







All Articles