invoking Query of GraphQL of Apollo Client

1.1k Views Asked by At

query screenshot

const allTeamApplicants = gql`
  query ($id: ID!) {
    allApplicants(filter: { user: { id: $id } }) {
      id
      firstName
      lastName
      appliedPosition
      applicationStage
      isFormFilled
      isContractSigned
      email
      phoneNumber
}

I use Apollo Client for GraphQL in React web app. Anyone knows how to invoke a query with parameters in an event, for example, I want to trigger the query with a parameter when a user clicks a button.

1

There are 1 best solutions below

2
On BEST ANSWER

To call a query in an event, instead of as in a higher order component, you should:

Import withApollo Hoc

import { withApollo } from 'react-apollo';

Wrap your component with withApollo

const component = withApollo(Component)

Inside your component, you will receive a new prop called client and you can use it as a Promise, such as:

function eventHandler(idParam) {
  client.query({
    query: gql`
      query ($id: ID!) {
        allApplicants(filter: { user: { id: $id } }) {
          id
          firstName
          lastName
          appliedPosition
          applicationStage
          isFormFilled
          isContractSigned
          email
          phoneNumber
        }
      }`,
      variables: {
        // set the variables defined in the query, in this case: query($id: ID!)
        id: idParam 
      }
    }
  })
  .then(...)
  .catch(...)
}

more info here: https://www.apollographql.com/docs/react/api/react-apollo.html#withApollo