Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 227
atkayla Avatar asked Oct 02 '16 07:10

atkayla


People also ask

How do you query a GraphQL in React?

To run a query within a React component, call useQuery and pass it a GraphQL query string. When your component renders, useQuery returns an object from Apollo Client that contains loading , error , and data properties you can use to render your UI.

Does Apollo Client use React query?

Now that we've set up Apollo Client, we can integrate it into our React app. This lets us use React Hooks to bind the results of GraphQL queries directly to our UI.


1 Answers

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.

like image 178
stubailo Avatar answered Oct 08 '22 08:10

stubailo