Apollo GraphQL React - how to query on click?

 ̄綄美尐妖づ 提交于 2019-11-27 00:17:21

问题


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?


回答1:


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.




回答2:


As of version 3.0, you can do this in two ways now.

client.query

The first way is to call ApolloClient's query method. This returns a Promise that will resolve to the query's result. You can get a reference to the client by using the withApollo HOC:

class MyComponent extends React.Component {
  handleClick() {
    const { data } = await this.props.client.query({
      query: gql`...`,
      variables: { ... },
    })
    ...
  }
  ...
}

withApollo(MyComponent)

Alternatively, you can also use ApolloConsumer to get the client:

const MyComponent = () => (
  <ApolloConsumer>
    {client => {
      ...
    }
  </ApolloConsumer>
)

or the useApolloClient hook:

const MyComponent = () => {
  const client = useApolloClient()
  ...
}

useLazyQuery

The second way is to use the useLazyQuery hook:

const MyComponent = () => {
  const [runQuery, { called, loading, data }] = useLazyQuery(gql`...`)
  const handleClick = () => runQuery({ variables: { ... } })
  ...
}


来源:https://stackoverflow.com/questions/39814853/apollo-graphql-react-how-to-query-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!