view raw
Tidus Smith Tidus Smith - 7 months ago 151
React JSX Question

Apollo GraphQL React - how to query on click?

In the Apollo React docs 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?


You can do it by passing a reference to Apollo Client using the withApollo higher-order-component, as documented here:

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

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

  render() { ... }


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.