0
votes

Most of the information out there about Apollo Client and GraphQL queries is about fetching data and immediately rendering something.

What about the common use case where I want to fetch data to, let say, update the state in which I clearly don't need to render JSX, I just want to run Javascript code.

Use the following code snippet as an example

onRefChange (formValues) {

    let { project, ref } = formValues
    let projectFound = find(this.state.projects, (o) => { return o.id === project.value } )

    let variables = {
      slug: projectFound.slug, ref: parseInt(ref)
    }
    console.info('variables ready', variables)
    return (
      <Query query={RESOLVE_REF} variables={variables}>
        { ({ data, error }) => {
          console.info('data response', data)
          console.info('error response', error)
          return data
        }}
      </Query>
    )
  }

Apollo forces me to use the Query component just to perform a query, even when I don't want to render anything. Also those console.info never log anything, but the variables ready text does appear.

I have found that the documentation is pretty clear on using the Query component, but obscure on every option which is different. I feel I'm missing something.

I'm also concerned about how Apollo doesn't seems respect the separation of responsibilities, apparently merging both data and presentation into a single responsibility (as is clear with the Query component), which in my current understanding is quite silly, but most likely I'm fucking things up.

Any insight is appreciated.

1

1 Answers

1
votes

As long as you've configured and included an ApolloProvider at the top of your component tree, you can get your query instance using either the withApollo HOC, or the ApolloConsumer:

const MyComponent = ({ client }) => {
 // use it!
}
withApollo(MyComponent)

<ApolloConsumer>
  {client => (
    // use it!
  )}
</ApolloConsumer>

You can then use any of the methods that are available to the client instance, including query and mutation, both of which return a Promise that resolves to an ApolloQueryResult object that includes data and errors. The full documentation for the client's API can be found here. Your code would then look something like:

async onRefChange (formValues) {
  let { project, ref } = formValues
  let projectFound = find(this.state.projects, (o) => { return o.id === project.value } )

  let variables = {
    slug: projectFound.slug, ref: parseInt(ref)
  }
  try {
    const { data } = await this.props.client(RESOLVE_REF, { variables })
  } catch (e) {
    // Handle errors
  }
}