Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
841 views
in Technique[技术] by (71.8m points)

reactjs - Apollo GraphQL React - how to query on click?

In the Apollo React docs http://dev.apollodata.com/react/queries.html#basics there are examples of fetching automatically when the component is shown, but I'd like to run a query when a button is clicked. I see an example to "re"fetch a query when a button is clicked, but I don't want it to query initially. I see there is a way to call mutations, but how do you call queries?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can do it by passing a reference to Apollo Client using the withApollo higher-order-component, as documented here: https://www.apollographql.com/docs/react/api/react-apollo.html#withApollo

Then, you can call client.query on the passed in object, like so:

class MyComponent extends React.Component {
  runQuery() {
    this.props.client.query({
      query: gql`...`,
      variables: { ... },
    });
  }

  render() { ... }
}

withApollo(MyComponent);

Out of curiosity, what's the goal of running a query on a click event? Perhaps there is a better way to accomplish the underlying goal.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...