Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

invoking Query of GraphQL of Apollo Client

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.

like image 608
Lawrence Avatar asked Sep 01 '17 01:09

Lawrence


People also ask

How do you query using Apollo Client?

Executing a query 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.

How do I get data from a GraphQL query?

In GraphQL, you fetch data with the help of queries. A query is a GraphQL Operation that allows you to retrieve specific data from the server. We ask the server for all the todos and their titles in the above query. The “ todos " represents an object and " title " a field.


1 Answers

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

like image 198
Pedro Baptista Afonso Avatar answered Oct 19 '22 23:10

Pedro Baptista Afonso